[英]Laravel - How can select data in 4 tables at a time using Eloquent ORM?
I have 4 tables: products
, attributes
, attribute_groups
, attribute_product
. 我有4个表:
products
, attributes
, attribute_groups
, attribute_product
。
Product - Attribute: Many to Many. 产品-属性:多对多。
Attribute - Attribute Group: One to Many. 属性-属性组:一对多。
Using Eloquent ORM, how can I fetch a nested object to show data like that: 使用雄辩的ORM,我如何获取嵌套对象以显示类似的数据:
@foreach($product->attributeGroups as $attributeGroup)
<div class="form-group">
<label>{{ $attributeGroup->name }}:</label>
{{ Form::select('attributes[$attributeGroup->id][]', $attributeGroup->attributes, null, ['class' => 'form-control input-sm']) }}
</div>
@endforeach
Within your Product model, simply added the following 在您的产品模型中,只需添加以下内容
class Product extends Eloquent {
protected $with = ['attributeGroups.attributes'];
public function attributeGroups() {
return $this->belongsToMany('AttributeGroup');
}
}
This will auto/eager load your relationships with every request of the Product resource model. 这将自动/渴望通过产品资源模型的每个请求加载您的关系。
Here is an example of what your AttributeGroup eloquent model should look like. 这是AttributeGroup雄辩模型的外观示例。
class AttributeGroup extends Eloquent {
protected $table = 'attribute_groups';
public function attributes() {
return $this->belongsToMany('Attribute');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.