How can the concept of Models in MVC be adapted to handle queries involving data from multiple tables in PHP frameworks?
When dealing with queries involving data from multiple tables in PHP frameworks, the concept of Models in MVC can be adapted by creating relationships between the models representing the different tables. By establishing relationships such as one-to-one, one-to-many, or many-to-many, you can easily retrieve and manipulate data across multiple tables in a structured and efficient manner.
// Example of creating a relationship between two models in a PHP framework
// User model representing the users table
class User extends Model {
public function posts() {
return $this->hasMany('Post');
}
}
// Post model representing the posts table
class Post extends Model {
public function user() {
return $this->belongsTo('User');
}
}
// Usage example
$user = User::find(1);
$posts = $user->posts;
foreach ($posts as $post) {
echo $post->title;
}