Jay
Jay

Reputation: 443

Laravel 5 Iterate and Limit models returned from Relationship

Using L5 I have a "Car" model and a "Brand" model.

In my Brand model I have a hasMany relationship for Car, so I can do $brand->cars and get all of the cars in my DB for that brand.

This works well, but I will never need to return all of them, I will always be filtering, limiting, or iterating over them.

In my controller I can do $brand->cars->take(20), which correctly returns 20 results, but inspecting the mysql query I can see that there is no 'limit' in the query itself which seems pretty intensive when you have millions of possible results.

Is there a way to iterate and limit directly on a relationship, or just I just abbandon the relationship and just use eloquent directly:

$brand::where('year','>',2010)->take(20)->get()?

Upvotes: 0

Views: 502

Answers (2)

Ezequiel Moreno
Ezequiel Moreno

Reputation: 2348

It is Eager loading what you are looking for.

Brand::with('cars')->take(20)->get();

if you need to filter cars based on any field, for example 'year':

Brand::whereHas('cars', function($q) use($year)
{
    $q->where('year', '>', $year);

})->with('cars')->take(20)->get();

Upvotes: 1

lowerends
lowerends

Reputation: 5267

Yes, you can use this:

$brand->cars()->take(20)->get();

Upvotes: 0

Related Questions