koalaok
koalaok

Reputation: 5740

How to eager load relationships on multiple levels?

I have the following models:

ProductA - ProductB - Feature - Option

I have the following relations:

ProductA belongsToMany ProductB ProductB belongsToMany Feature Feature belongsToMany Option

When I want to see details of ProductA, (a post with ProductA id, that will be managed by a controller) I'd like to eager load all the relationships to pass a variable containing all the details to the view.

Is it possible with a single Eloquent instruction?

Something like this (I know it's not working): is it the correct way?

$prodcutDetails = ProductA->with('product_b')->with('features')->with('option')->find($id);

Thanks

Upvotes: 0

Views: 707

Answers (2)

Todd
Todd

Reputation: 581

@Jerodev gives a good answer above, but the multiple relations are redundant; using $prodcutDetails = ProductA::with('product_b.features.option')->find($id); would be more efficient and you still have access to product_b and product_b.features.

Upvotes: 1

Jerodev
Jerodev

Reputation: 33186

You can use the dot notation to eager load relations of relations. Like so:

$prodcutDetails = ProductA::with(['product_b', 'product_b.features', 'product_b.features.option'])->find($id);

Upvotes: 1

Related Questions