Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

You can't do it with eager loading. Moreover it's pretty hard to do in SQL as you would need many subqueries to limit joined rows. So instead load everything and limit comments in php or lazy eager load recent comments.

To do the latter you can use something like this on your Post model to make things easier:

public function commentsRecent()
{
    return $this->hasMany('Comment')->orderBy('created_at', 'desc')->limit(3);
}
Last updated 2 years ago.

moh1434 liked this reply

1

I have found the solution. Try this!

$lines = \Category::where('status', \Category::STATUS_PUBLISH)
            ->with(['firstThreeComment'])
            ->get()
			->map(function( $category ){
				$category->firstThreeComment = $category->firstThreeComment->take(3);
				return $category;
});
Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

tzookb tzookb Joined 9 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.