laravel eloquent 嵌套 SELECT 语句
laravel eloquent nested SELECT statement
我正在使用 Laravel 和 Eloquent 以及 MySQL。
我有三个 tables POSTS
、USERS
和 COMMENTS
。我的 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
table 中获取每个用户的详细信息。我不想使用 foreach()
然后获取每个 ID
的详细信息。有什么方法可以让我在一次调用中获得所有评论(来自 COMMENTS
table),包括用户详细信息(来自 USER
table)。
这应该有效。请尝试以下操作:
$comment = Comment::where('post_id', $post->id)->with('user')->paginate(10);
您首先需要在 USERS 和 COMMENTS 中创建一对多关系(用户有很多评论)。
然后你已经有关系post有很多评论关系。
所以,让我们使用嵌套预加载
$post = Post::where('id', $id)->with('comments.user')->get();
return view('posts\single', ['post' => $post]);
现在在您的 blade 个文件中....
$post->comments
将为您提供特定 post 的所有评论。
$post->comments->user
会给你发表评论的用户。
请试试这个 -
User::join('posts','posts.created_by','=','users.id')
->with('comment')
->where('posts.id' ,'=' ,$id)
->paginate(10);
希望对您有所帮助。
我正在使用 Laravel 和 Eloquent 以及 MySQL。
我有三个 tables POSTS
、USERS
和 COMMENTS
。我的 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
table 中获取每个用户的详细信息。我不想使用 foreach()
然后获取每个 ID
的详细信息。有什么方法可以让我在一次调用中获得所有评论(来自 COMMENTS
table),包括用户详细信息(来自 USER
table)。
这应该有效。请尝试以下操作:
$comment = Comment::where('post_id', $post->id)->with('user')->paginate(10);
您首先需要在 USERS 和 COMMENTS 中创建一对多关系(用户有很多评论)。
然后你已经有关系post有很多评论关系。
所以,让我们使用嵌套预加载
$post = Post::where('id', $id)->with('comments.user')->get();
return view('posts\single', ['post' => $post]);
现在在您的 blade 个文件中....
$post->comments
将为您提供特定 post 的所有评论。$post->comments->user
会给你发表评论的用户。
请试试这个 -
User::join('posts','posts.created_by','=','users.id')
->with('comment')
->where('posts.id' ,'=' ,$id)
->paginate(10);
希望对您有所帮助。