如何使用 laravel eloquent 连接 3 个表
How to join 3 tables using laravel eloquent
如何在 laravel 5 中应用此查询?
我有 3 table、Post、个人资料、评论
Post{id,title,body,user_id}
profile{user_id,last_name,first_name}
comments{comments,user_id,post_id}
我想得到这样的结构:
post_id title post last_name first_name
以下为评论
comments last_name fist_name
如果您只需要这些列,则必须执行以下操作:
$users = DB::table('comments')
->join('profile', 'comments.user_id', '=', 'profile.user_id')
->select('comments.comments', 'profile.last_name', 'profile.first_name')
->get();
无论如何,如果您在不同的地方(或不同的结构)使用数据,我建议您在模型中使用关系。
P.S:
post_id post last_name first_name
任何 table 中都没有 "post" 字段,您需要 post 标题吗?
//post型号
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();
然后就可以了:)
感谢您的帮助和想法:)
如何在 laravel 5 中应用此查询? 我有 3 table、Post、个人资料、评论
Post{id,title,body,user_id}
profile{user_id,last_name,first_name}
comments{comments,user_id,post_id}
我想得到这样的结构:
post_id title post last_name first_name
以下为评论
comments last_name fist_name
如果您只需要这些列,则必须执行以下操作:
$users = DB::table('comments')
->join('profile', 'comments.user_id', '=', 'profile.user_id')
->select('comments.comments', 'profile.last_name', 'profile.first_name')
->get();
无论如何,如果您在不同的地方(或不同的结构)使用数据,我建议您在模型中使用关系。
P.S:
post_id post last_name first_name
任何 table 中都没有 "post" 字段,您需要 post 标题吗?
//post型号
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();
然后就可以了:) 感谢您的帮助和想法:)