【问题标题】:Complex relationship formation in Laravel 5Laravel 5 中的复杂关系形成
【发布时间】:2019-04-27 13:35:59
【问题描述】:

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

类别组模型

// 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】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2014-01-16
      • 1970-01-01
      • 2015-01-27
      相关资源
      最近更新 更多