Joshua Hansen
Joshua Hansen

Reputation: 405

Laravel - How can select data in 4 tables at a time using Eloquent ORM?

I have 4 tables: 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:

@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

Upvotes: 0

Views: 103

Answers (1)

verheesj
verheesj

Reputation: 1458

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.

class AttributeGroup extends Eloquent {
      protected $table = 'attribute_groups';

      public function attributes() {
           return $this->belongsToMany('Attribute');
      }
}

Upvotes: 1

Related Questions