Let's say I have these 2 tables:
Users: id, name
Posts: id, user_id, created_at
I am trying to get 2 most recent posts of each user. I have the relationship models set up correctly. At first I thought I could just use ->take(2) but that only returns 2 rows from the whole query.
This is what I have now:
$user->load(['posts' => function($query) {
$query->orderBy('id', 'desc');
}]);
That will return all posts for each user. It's really not a problem right now but if users have hundreds or thousands of posts, that will become a memory hog quickly.
What's the best way to get last 2 records of each user with hopefully using eager loading? I could easily do it by fetching last 2 records of each user but that's too many queries.
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TAGnIX
via IFTTT
Aucun commentaire:
Enregistrer un commentaire