Search code examples
laraveleloquent-relationship

laravel multi-level many to many


I have 3 models, Industry, Category, Machine and they are linked as following

  • Industry can have multiple Categories, and a Category can be in only one Industry (industry Id stored in category table)
  • A category can have multiple machines, and a machine can be in multiple Categories (using pivot table)

Problem : I want to show all machines in an industry, how i can do that?

What I did so far : I retrieved all category ids related to a specific industry like : $industry->categories()->pluck("id"). I don't know what I can do next to get all machines


Solution

  • Industry model relation:

    class Industry {
        public function categories(){
            return $this->hasMany(Category::class);
        }
    }
    

    Category model relation:

    class Category {
        public function indusry(){
            return $this->hasOne(Industry::class);
        }
    
        public function machines(){
            return $this->belongsToMany(Machine::class);
        }
    }
    

    Machine model relation:

    class Machine {
        public function categories(){
            return $this->belongsToMany(Category::class);
        }
    }
    

    you can use whereHas method like this:

    $machines = Machine::whereHas('categories', function($query) {
        $query->whereHas('indusry', function($sub_query) {
            $sub_query->where('name', {your_industry});
        });
    });