[英]Laravel eloquent eager load two pivot 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
}
}
我如何获得具有渴望加载它们的能力的Category模型中的所有属性?
在类别模型中,您可以使用属性和属性组将两个关系定义为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');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.