Laravel 5中的复杂关系形成

问题描述 投票:0回答:1

我正在开发一个复杂的购物车项目。我有这样的关系

CategoryGroup模型

// App\CategoryGroup

class CategoryGroup extend Model 
{

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

分类模型

// 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'
        );
    }

}

产品型号

// App\Product

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

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

库存模型

// App\Inventory

class Inventory extend Model 
{

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

现在我陷入了需要在CategoryGroups和Inventory模型之间建立关系的情况,如下所示:

// 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
    }

}

有没有一种很好的方式来实现这种关系?

laravel-5 eloquent laravel-5.5 laravel-query-builder eloquent--relationship
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]
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.