Php laravel雄辩的嵌套SELECT语句
我正在将Laravel与Elount一起用于MySQL。Php laravel雄辩的嵌套SELECT语句,php,laravel,laravel-5,laravel-5.2,laravel-5.3,Php,Laravel,Laravel 5,Laravel 5.2,Laravel 5.3,我正在将Laravel与Elount一起用于MySQL。 我有三个表帖子,用户和评论。我的POST和COMMENT是一对多的关系,因此通过下面的代码,我可以得到特定POSTid的注释列表 $post = Post::where('id', $id)->get(); $comment = Post::find($id)->comment()->paginate(10); return view('posts\single', ['post' => $post
我有三个表
帖子
,用户
和评论
。我的POST
和COMMENT
是一对多的关系,因此通过下面的代码,我可以得到特定POST
id的注释列表
$post = Post::where('id', $id)->get();
$comment = Post::find($id)->comment()->paginate(10);
return view('posts\single', ['post' => $post, 'comments' => $comment]);
现在我想从
user
表中获取每个用户的详细信息。我不想使用foreach()
然后获取每个ID
的详细信息。是否有任何方法可以让我在一次通话中获得所有评论(来自评论
表),包括用户详细信息(来自用户
表) 这应该行得通。请尝试以下操作:
$comment = Comment::where('post_id', $post->id)->with('user')->paginate(10);
首先需要在“用户到评论”中创建一对多关系(用户有许多评论) 然后你已经有了关系发表了很多评论关系 所以,让我们使用嵌套的即时加载
$post = Post::where('id', $id)->with('comments.user')->get();
return view('posts\single', ['post' => $post]);
现在在您的刀片文件中
将为您提供特定帖子的所有评论李>$post->comments
将为您提供发表评论的用户$post->comments->user
User::join('posts','posts.created_by','=','users.id')
->with('comment')
->where('posts.id' ,'=' ,$id)
->paginate(10);
希望这对您有所帮助。使用
加入?您必须使用雄辩的关系..不幸的是,这在关键用户处返回NULL,正如“user”=>NULLWell解释的那样!非常感谢,莫利克。工作方式与Charlmwelcome:)您应该单击向下箭头下的勾选按钮将其标记为已回答。