复杂的关系形成在Laravel 5

时间:2018-11-25 21:21:05

标签: laravel-5 eloquent laravel-5.5 laravel-query-builder eloquent--relationship

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

类别组模型

void ff(int x);

void gg(double y) {
    ff(y); // how would you know if this makes sense?
    int x=y; //how would you know if this makes sense?
}
void ggg(double x) {
    int x1 = x; // truncate x
    int x2 = int(x);
    int x3 = static_cast<int>(x); // very explicit conversion (17.8)

    ff(x1);
    ff(x2);
    ff(x3);

    ff(x); // truncate x
    ff(int(x));
    ff(static_cast<int>(x)); // very explicit conversion (17.8)
}

类别模型

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

现在,我陷入了需要在CategoryGroups和Inventory模型之间建立关系的情况,像这样:

// App\Inventory

class Inventory extend Model 
{

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

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

1 个答案:

答案 0 :(得分: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]
        );
    }
}