Eloquent filter by child relationship

Viewed 36

I have a Laravel application that shows lists of cars make, model, year, trim.

When page loads list of make is displayed, user then clicks specific make and all model are displayed, etc.

These are my tables (already created relationships):

make

- id

model

- id
- id_make

year

- id
- id_model

trim

- id
- id_year

When showing list of make, how can i query only make with at least one model with at least one year with at least one trim?

1 Answers

this is simple query :

Make::query()->whereHas('model',function ($query){
    $query->whereHas('year',function ($query2){
        $query2->whereHas('trim',function ($query3){
            $query3->orderByDesc('id');
        });
    });
})
    ->get();

also you can add condition like this

Make::query()->whereHas('model', function ($query) {
    $query->whereHas('year', function ($query2) {
        $query2->whereHas('trim', function ($query3) {
            $query3->orderByDesc('id');
        })
            ->orderByDesc('id');
    })
        ->orderByDesc('id');
})
    ->orderByDesc('id')
    ->get();

but it's not good

better to use deep relationship read bellow package document

https://github.com/staudenmeir/eloquent-has-many-deep

Related