Laravel eloquent 预加载两个数据透视表
Laravel eloquent eager load two pivot tables
我正在尝试加载一个通过组拼接的属性和另一个 table 具有额外相关枢轴的属性。
这是 tables:
Categories
--------------------
id
Attributes
--------------------
id
attribute_set_id
Attribute_Groups
----------------------------
id
Categories_Attribute_Groups
-----------------------------
category_id
attribute_group_id
Categories_Additional_Attributes
-----------------------------
category_id
attribute_id
Class Category extends eloquent
{
// how to achieve this
public function attributes()
{
// all attributes that can be eager load
}
}
如何获取类别模型中的所有属性并能够预先加载它们?
在类别模型中,您可以将 2 个关系定义为 belongsToMany
与属性和属性组
Class Category extends eloquent
{
public function attributes()
{
return $this->belongsToMany(Attribute::class, 'Categories_Additional_Attributes', 'category_id');
}
public function attribute_groups()
{
return $this->belongsToMany(AttributeGroups::class, 'Categories_Attribute_Groups', 'category_id');
}
}
现在您可以像
Category::with(['attributes', 'attribute_groups'])->get();
对于双向映射,您可以将它们定义为
Class Attribute extends eloquent
{
public function categories()
{
return $this->belongsToMany(Category::class, 'Categories_Additional_Attributes', 'attribute_id');
}
}
Class AttributeGroups extends eloquent
{
public function categories()
{
return $this->belongsToMany(Category::class, 'Categories_Attribute_Groups', 'attribute_group_id');
}
}
我正在尝试加载一个通过组拼接的属性和另一个 table 具有额外相关枢轴的属性。 这是 tables:
Categories
--------------------
id
Attributes
--------------------
id
attribute_set_id
Attribute_Groups
----------------------------
id
Categories_Attribute_Groups
-----------------------------
category_id
attribute_group_id
Categories_Additional_Attributes
-----------------------------
category_id
attribute_id
Class Category extends eloquent
{
// how to achieve this
public function attributes()
{
// all attributes that can be eager load
}
}
如何获取类别模型中的所有属性并能够预先加载它们?
在类别模型中,您可以将 2 个关系定义为 belongsToMany
与属性和属性组
Class Category extends eloquent
{
public function attributes()
{
return $this->belongsToMany(Attribute::class, 'Categories_Additional_Attributes', 'category_id');
}
public function attribute_groups()
{
return $this->belongsToMany(AttributeGroups::class, 'Categories_Attribute_Groups', 'category_id');
}
}
现在您可以像
Category::with(['attributes', 'attribute_groups'])->get();
对于双向映射,您可以将它们定义为
Class Attribute extends eloquent
{
public function categories()
{
return $this->belongsToMany(Category::class, 'Categories_Additional_Attributes', 'attribute_id');
}
}
Class AttributeGroups extends eloquent
{
public function categories()
{
return $this->belongsToMany(Category::class, 'Categories_Attribute_Groups', 'attribute_group_id');
}
}