Laravel雄辩地:将相关模型分组(例如,所有用于收集帖子的评论)

时间:2018-08-26 13:55:58

标签: laravel eloquent

要获取单个帖子的评论:Post::find(1)->comments()

要获取多个帖子:Post::whereBetween('id',[1,10])

如何获取多个帖子的所有合并评论?
Post::whereBetween('id',[1,10])->comments()

3 个答案:

答案 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();
相关问题