要获取单个帖子的评论:Post::find(1)->comments()
要获取多个帖子:Post::whereBetween('id',[1,10])
如何获取多个帖子的所有合并评论?
Post::whereBetween('id',[1,10])->comments()
答案 0 :(得分:2)
使用pluck()
:
$posts = Post::whereBetween('id', [1, 10])->with('comments')->get();
$comments = $posts->pluck('comments')->flatten();
答案 1 :(得分:1)
您可以使用此
$posts = Post::whereBetween('id',[1,10])->with('comments')->get();
或者如果您不会只收到评论
$comments = App\Comment::whereHas('post', function ($query) {
$query->whereBetween('id', [1, 10]);
})->get();
或者相关的主键post_id
$comments = App\Comment::whereBetween('post_id', [1, 10])->get();
答案 2 :(得分:1)
如果您只想发表评论,并假设您在Comment模型中有一个 post_id 字段,并且您已经指出了该帖子的ID:
$comments = Comment::whereIn('post_id', [1,2,3,4,5,6,7,8,9,10])->get();