Laravel - 如何使用Eloquent ORM一次选择4个表中的数据?

时间:2015-03-21 18:20:37

标签: php laravel orm eloquent

我有4个表:productsattributesattribute_groupsattribute_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

1 个答案:

答案 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');
      }
}