Search code examples
mysqllaraveleloquenteager-loading

Laravel eloquent eager load two pivot tables


I'm trying to eager load one attribute which is spliced through a group and another table with additionally related pivot. Here's are tables:

Categories
--------------------
id

Attributes
--------------------
id
attribute_set_id


Attribute_Groups
----------------------------
id


Categories_Attribute_Groups
-----------------------------
category_id
attribute_group_id


Categories_Additional_Attributes
-----------------------------
category_id
attribute_id


Class Category extends eloquent
{

    // how to achieve this
    public function attributes()
    {
        // all attributes that can be eager load
    }
}

How can I get all attributes in Category model with the ability to eager load them ?


Solution

  • In category model you can define 2 relations as belongsToMany with attribute and attribute group

    Class Category extends eloquent
    {
    
        public function attributes()
        {
            return $this->belongsToMany(Attribute::class, 'Categories_Additional_Attributes', 'category_id');
        }
    
        public function attribute_groups()
        {
            return $this->belongsToMany(AttributeGroups::class, 'Categories_Attribute_Groups', 'category_id');
        }
    }
    

    Now you can eager them as

    Category::with(['attributes', 'attribute_groups'])->get();
    

    For bidirectional mapping you can define these as

    Class Attribute extends eloquent
    {
    
        public function categories()
        {
            return $this->belongsToMany(Category::class, 'Categories_Additional_Attributes', 'attribute_id');
        }
    }
    
    Class AttributeGroups extends eloquent
    {
    
        public function categories()
        {
            return $this->belongsToMany(Category::class, 'Categories_Attribute_Groups', 'attribute_group_id');
        }
    }