user1012181
user1012181

Reputation: 8726

Sort collection by eager load value

I've a brand table, models table, categories table.

brand have hasMany relation with models, models has belongsTo relation to brand, categories has belongsToMany relation with models table. Everything works fine.

Now, how can I get all models of a brand within a specific category?

I've tried this:

$categories = Category::with(['models'=>function($query) use ($brand_name){
            $query->with(['brand'=>function($query) use ($brand_name){
                $query->where('name', $brand_name);
            }]);
        }])->where('name', 'presses')->first();

But it has the same effect as of selecting all models within a specific category. It's not filtering the brand name.

How can I do this?

Upvotes: 0

Views: 75

Answers (1)

oseintow
oseintow

Reputation: 7381

Try this and let see how it goes

$categories = Category::with(['models'=>function($query) use ($brand_name){
     $query->whereHas('brand', function($query) use ($brand_name){
         $query->where('name', $brand_name);
     });
 },'models.brand'])->where('name', 'presses')->first();

Upvotes: 1

Related Questions