在 Laravel 中加载所有关系及其子项
Load all relations and their children in Laravel
我有一个包含多个关系的相当复杂的结构。如果我的关系是这样定义的,我怎样才能在一次调用中加载所有关系?
Model
(has many) ChildModels1
Child1a
Child1b
...
(has many) ChildModels2
Child2a
Child2b
...
(has many) ChildModels3
Child3a
Child3a
Child3aa
Child3ab
...
我可以做到以下几点:
$entity = Entity::find($id)->load('ChildModels1', 'ChildModels2', 'ChildModels3');
但我也不确定如何加载所有子关系。
这可以通过预加载来实现:
Entity::where('id', $id)->with('relation1.subrelation1', 'relation1.subrelation2', 'relation2.subrelation1', 'relation2.subrelation2')->get();
When accessing Eloquent relationships as properties, the relationship
data is "lazy loaded". This means the relationship data is not
actually loaded until you first access the property. However, Eloquent
can "eager load" relationships at the time you query the parent model.
Eager loading alleviates the N + 1 query problem.
您可以在 Laravel documentation on eager loading 中阅读更多相关信息。
我有一个包含多个关系的相当复杂的结构。如果我的关系是这样定义的,我怎样才能在一次调用中加载所有关系?
Model
(has many) ChildModels1
Child1a
Child1b
...
(has many) ChildModels2
Child2a
Child2b
...
(has many) ChildModels3
Child3a
Child3a
Child3aa
Child3ab
...
我可以做到以下几点:
$entity = Entity::find($id)->load('ChildModels1', 'ChildModels2', 'ChildModels3');
但我也不确定如何加载所有子关系。
这可以通过预加载来实现:
Entity::where('id', $id)->with('relation1.subrelation1', 'relation1.subrelation2', 'relation2.subrelation1', 'relation2.subrelation2')->get();
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.
您可以在 Laravel documentation on eager loading 中阅读更多相关信息。