问题
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
回答1:
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);
回答2:
@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
.
来源:https://stackoverflow.com/questions/41563734/how-to-eager-load-relationships-on-multiple-levels