Reputation: 541
I have two tables - Posts and Comments. The relationship between them is one-to-many. A Post has many comments.
I am trying to get a list of all Posts with their latest 2 Comments
I have tried this:
$posts = Post::with(['comments'=>function($query){
$query->latest()->take(2)->get();
}])->get();
But it seems to be working only for the first Post;
Upvotes: 2
Views: 930
Reputation: 101
If your n stays constant, for example: getting the latest 3 comments, you can set up the relation in the model this way:
public function latestComments() {
return $this->hasMany(Comment::class)->latest()->take(3);
}
In your controller, you can simply use:
$posts = Post::with('latestComments')->get();
If your n keeps changing, you can follow this thread: Link
Upvotes: 0
Reputation: 11711
Laravel doesn't offer this functionality out of the box as discussed here https://github.com/laravel/framework/issues/18014 and documented here https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads, but there is a package that you can use to achieve this.
Take a look at https://github.com/staudenmeir/eloquent-eager-limit
Upvotes: 1