Laravel 5 如何使用laravel eloquent连接3个表

Laravel 5 如何使用laravel eloquent连接3个表,laravel-5,model,eloquent,relation,Laravel 5,Model,Eloquent,Relation,如何在laravel 5中应用此查询? 我有3个表格,帖子,个人资料,评论 Post{id,title,body,user_id} profile{user_id,last_name,first_name} comments{comments,user_id,post_id} 我想得到这种结构: post\u id title post last\u name first\u name 下面是评论 注释last\u name first\u name如果您只需要这些列,您必须执行以下操作: $

如何在laravel 5中应用此查询? 我有3个表格,帖子,个人资料,评论

Post{id,title,body,user_id}
profile{user_id,last_name,first_name}
comments{comments,user_id,post_id}
我想得到这种结构:

post\u id title post last\u name first\u name

下面是评论


注释last\u name first\u name

如果您只需要这些列,您必须执行以下操作:

$users = DB::table('comments')
        ->join('profile', 'comments.user_id', '=', 'profile.user_id')
        ->select('comments.comments', 'profile.last_name', 'profile.first_name')
        ->get();
无论如何,如果在不同的地方(或不同的结构)使用数据,我建议在模型中使用关系

附言:

任何表中都没有“post”字段,您需要post标题吗?

//post model

public function comments(){
    return $this->hasMany('App\Comments', 'post_id', 'id');
}
//评论模型

public function user(){
    return $this->belongsTo('App\Profile', 'user_id');
}
//剖面模型

public function comments(){
    return $this->hasMany('App\Comments');
}
我在控制器中调用它,使用:

$posts = Posts::with('userProfile','comments', 'comments.user')->get();
然后它就起作用了:)
感谢您的帮助和想法:)

这不是在后台对每个帖子项目进行三次不同的数据库查询吗?这是值得遵循的最佳解决方案吗?
$posts = Posts::with('userProfile','comments', 'comments.user')->get();