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?