Limiting relationships in Laravel
Asked Answered
B

1

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?

Bridgid answered 23/9, 2014 at 20:44 Comment(2)
Duplicate of #24344238. Also take a look at this softonsofa.com/…Bannister
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 :)Bridgid
M
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();
Mahdi answered 14/4, 2016 at 21:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.