2

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;

Mostafa Abedi
  • 541
  • 6
  • 19
  • similar issue this might help you. Ref:https://stackoverflow.com/questions/68422673/sub-query-with-eloquent-relationship/68422825#68422825 – John Lobo Jul 21 '21 at 03:06

2 Answers2

1

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

Abishek
  • 11,191
  • 19
  • 72
  • 111
0

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

stephen strange
  • 101
  • 1
  • 2