如何在laravel 5中应用此查询? 我有3个表,帖子,个人资料,评论
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
答案 0 :(得分:19)
//发布模型
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();
我用控制器在控制器中调用它:
log(n)
然后它工作:) 感谢您的帮助和想法:)
答案 1 :(得分:0)
首先,您应该使用Artisan为您制作模型,例如您创建发布模型。
然后您可以这样做:
$rows = Post::selectRaw('comments.post_id, post.body as post ,profile.last_name, profile.first_name' , comments.comments)->
join('profile' , 'post.user_id' ,'=' , 'profile.user_id')->
join('comments' , 'post.id' , '=' , 'comments.post_id')->
get() ;
现在您可以从 $ rows 访问您需要的任何内容,如下所示:
foreach($rows as $key=>$row){
echo $row->post_id;
}
答案 2 :(得分:-1)
如果您只需要这些列,您必须执行以下操作:
$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
没有"帖子"任何表格中的字段,你需要帖子标题吗?