Reputation: 2663
To get the comments for a single Post: Post::find(1)->comments()
To get multiple Posts: Post::whereBetween('id',[1,10])
How to get all the combined comments for multiple Posts?
A la Post::whereBetween('id',[1,10])->comments()
Upvotes: 0
Views: 76
Reputation: 8618
You can use this
$posts = Post::whereBetween('id',[1,10])->with('comments')->get();
Or if you wont to get only comments
$comments = App\Comment::whereHas('post', function ($query) {
$query->whereBetween('id', [1, 10]);
})->get();
Or if related primary key post_id
$comments = App\Comment::whereBetween('post_id', [1, 10])->get();
Upvotes: 1
Reputation: 354
If you just want the comments, and assuming you have a post_id field in your Comment model, and you have the ids of the posts as you've indicated:
$comments = Comment::whereIn('post_id', [1,2,3,4,5,6,7,8,9,10])->get();
Upvotes: 1
Reputation: 25906
Use pluck()
:
$posts = Post::whereBetween('id', [1, 10])->with('comments')->get();
$comments = $posts->pluck('comments')->flatten();
Upvotes: 2