In Laravel, performing a multi-table join query can be achieved using Eloquent ORM. Here is an example code where we have two tables, posts and comments, and we need to retrieve each post along with all associated comments.
// 在Post模型中定义关联关系
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
// 在Comment模型中定义关联关系
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
// 在控制器中进行联合查询
$posts = Post::with('comments')->get();
// 遍历结果
foreach ($posts as $post) {
echo $post->title;
foreach ($post->comments as $comment) {
echo $comment->content;
}
}
In the code above, the with method of Eloquent ORM is used for performing relational queries. By defining the relationships between models, it becomes easy to execute multi-table join queries.