我正在处理一个复杂的购物车项目。我有这样的关系
类别组模型
// AppCategoryGroup
class CategoryGroup extend Model
{
public function categories()
{
return $this->hasMany(Category::class);
}
}
类别模型
// AppCategory
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'
);
}
}
产品型号
// AppProduct
class Product extend Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
public function listings()
{
return $this->hasMany(Inventory::class);
}
}
库存模型
// AppInventory
class Inventory extend Model
{
public function products()
{
return $this->belongsTo(Product::class);
}
}
现在我陷入了这样一种情况,我需要在分类组和库存模型之间建立一种关系:
// AppCategoryGroup
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 AppCategory would be great
}
}
有没有一个好的方法来实现这种关系?
Laravel对直接关系没有本地支持。
我为这样的案例创建了一个包:https://github.com/staudenmeir/eloquent-has-many-deep
你可以这样使用它:
class CategoryGroup extends Model {
use StaudenmeirEloquentHasManyDeepHasRelationships;
public function inventories() {
return $this->hasManyDeep(
Inventory::class,
[Category::class, 'category_product', Product::class]
);
}
}