How to eager load relationships on multiple levels?

回眸只為那壹抹淺笑 提交于 2020-01-25 16:49:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!