Relationship limitation in Laravel

I have a Post model that has hasMany ('Comments'). I would like to receive all posts with comments, but only the last comment for each post. And since there are thousands of posts with thousands of comments each, this option is not possible due to performance problems (that is, downloading all the comments for each post, and then executing $ post-> comments [0] โ†’ value):

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

I can not, too:

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

since it just doesn't work.

I am absolutely sure that I am not the only one who has this problem, and I managed to find some โ€œsolution attemptsโ€, but not a stable example of working code. Can anyone help?

+6
source share
1 answer

try the following: let's say you define a โ€œcommentsโ€ relation to your Post model. here is how you can relate all the comments to this:

 App\Post::all()->comments()->orderBy('comments.created_at')->take(1)->get(); 
+2
source

Source: https://habr.com/ru/post/975739/


All Articles