Hello. I have such a table

categories: id | name | slug, hasMany('App\Product') Products: id | name | slug | category_id | brand_id, belongsTo('App\Category'), belongsTo('App\Brand') Brands: id | name | slug |, hasMany('App\Product') 

The problem is that when I try to bring manufacturers into the category with this function

 // category model public function brands() { return $this->hasManyThrough('App\Brand', 'App\Product' 'brand_id', 'id'); } 

That producers either are not displayed, or are not displayed correctly (not in its category). Is there any other way to get manufacturers through products?

    1 answer 1

    The hasManyThrough relation works for the case.
    Model 1 -> hasMany -> Model 2 -> hasMany -> Model3
    Model 1 -> hasManyThrough -> Model 3

    In your case it is

    Category -> hasMany -> Product -> belongsTo -> Brand

    Try changing the relationship of Product::brands to hasOne or hasMany . Semantically, this is not very correct, but it should almost break nothing, it works about the same.

    • Thank you for the clarification. Solved it in this way public function brands ($ ids = []) {return Brand :: whereHas ('products', function ($ q) use ($ ids) {$ q-> whereIn ('id', $ ids); }) -> get (); }}} - Alex_01