6

I have a model Post which has a hasMany('Comments') relationship. I would like to fetch all Posts with the Comments relationship, but only the latest one comment for each Post. And because there are thousands of posts with thousands of comments each, an option such as this is not possible due to performance issues (i.e. loading all comments for each post and then doing $post->comments[0]->value):

Post::with('comments' => function($query){
    $query->orderBy('created_at','desc')
});

Nor can I do:

Post::with('comments' => function($query){
    $query->orderBy('created_at','desc')->limit(1)
});

as this just doesn't work.

I am completely sure I'm not the only one with this issue and I did manage to find some 'attempts for a solution' but not a stable example of working code. Can anyone help please?

Yasen Slavov
  • 787
  • 4
  • 16
  • 2
    Duplicate of http://stackoverflow.com/questions/24343738/getting-just-the-latest-value-on-a-joined-table-with-eloquent#24350807. Also take a look at this http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/ – Jarek Tkaczyk Sep 23 '14 at 21:07
  • Brilliant, I will try it tonight. If you want you can post it as the answer so that I can mark it as the best answer :) – Yasen Slavov Sep 24 '14 at 07:08

1 Answers1

2

try this one: lets say you have defined the "comments" relation on your Post model. this is how you can take all the comments belong to that:

App\Post::all()->comments()->orderBy('comments.created_at')->take(1)->get();
Salar
  • 5,305
  • 7
  • 50
  • 78