我有4个表:products
,attributes
,attribute_groups
,attribute_product
。
产品 - 属性:多对多。
属性 - 属性组:一对多。
使用Eloquent 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
答案 0 :(得分:1)
在您的产品型号中,只需添加以下内容
即可class Product extends Eloquent {
protected $with = ['attributeGroups.attributes'];
public function attributeGroups() {
return $this->belongsToMany('AttributeGroup');
}
}
这将自动/急切地加载您与产品资源模型的每个请求的关系。
以下是您的AttributeGroup雄辩模型的示例。
class AttributeGroup extends Eloquent {
protected $table = 'attribute_groups';
public function attributes() {
return $this->belongsToMany('Attribute');
}
}