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?

4

1 回答 1

0

Laravel 没有对直接关系的原生支持。

我为这样的案例创建了一个包:https ://github.com/staudenmeir/eloquent-has-many-deep

你可以像这样使用它:

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

    public function inventories() {
        return $this->hasManyDeep(
            Inventory::class,
            [Category::class, 'category_product', Product::class]
        );
    }
}
于 2018-11-26T01:47:51.807 回答