0

I'm working on a complex shopping cart project. I have relationships like this

CategoryGroup model

// App\CategoryGroup

class CategoryGroup extend Model 
{

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

Category model

// App\Category

class Inventory extend Model 
{

    public function categoryGroup()
    {
        return $this->belongsTo(CategoryGroup::class);
    }


    public function products()
    {
        return $this->belongsToMany(Product::class);
    }


    public function listings()
    {
        return $this->belongsToMany(
                                   Inventory::class, 
                                   'category_product', 
                                   null,
                                   'product_id',
                                   null,
                                   'product_id'
        );
    }

}

Product model

// App\Product

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

    public function listings()
    {
        return $this->hasMany(Inventory::class);
    }
}

Inventory model

// App\Inventory

class Inventory extend Model 
{

    public function products()
    {
        return $this->belongsTo(Product::class);
    }
}

Now I'm stuck on the situation where I need to create a relationship between The CategoryGroups and the Inventory model like this:

// App\CategoryGroup

class CategoryGroup extend Model 
{

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


    public function listings()
    {
        // Can't figured out the way
        // A belongsToMany like the App\Category would be great
    }

}

Is there a good way to achieve this kind of relationship?

Munna Khan
  • 1,902
  • 1
  • 18
  • 24

1 Answers1

0

Laravel has no native support for a direct relationship.

I created a package for cases like this: https://github.com/staudenmeir/eloquent-has-many-deep

You can use it like this:

class CategoryGroup extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function inventories() {
        return $this->hasManyDeep(
            Inventory::class,
            [Category::class, 'category_product', Product::class]
        );
    }
}
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109