I really tried to understand the difference between the with()
method and the load()
method, but couldn't really understand.
在我看来,使用with()
方法"更好",因为我渴望加载关系.似乎如果我使用load()
,我加载关系就像我使用hasMany()
(或任何其他与对象之间的关系相关的方法).
我弄错了吗?
I really tried to understand the difference between the with()
method and the load()
method, but couldn't really understand.
在我看来,使用with()
方法"更好",因为我渴望加载关系.似乎如果我使用load()
,我加载关系就像我使用hasMany()
(或任何其他与对象之间的关系相关的方法).
我弄错了吗?
Both accomplish the same end results—eager loading a related model onto the first. In fact, they both run exactly the same two queries. The key difference is that with()
eager loads the related model up front, immediately after the initial query (all()
, first()
, or find(x)
, for example); when using load()
, you run the initial query first, and then eager load the relation at some later point.
这里的"Eager "意味着我们将一个特定结果集的所有相关模型关联起来,而不是必须运行n个查询,其中n是初始集合中的项数.
Eager loading using with()
If we eager load using with()
, for example:
$users = User::with('comments')->get();
...如果我们有5个用户,将立即运行以下两个查询:
select * from `users`
select * from `comments` where `comments`.`user_id` in (1, 2, 3, 4, 5)
...我们最终得到了一组模型,这些模型的注释附在用户模型上,所以我们可以做$users->comments->first()->body
个这样的事情.
"Lazy" eager loading using load()
Or, we can separate the two queries, first by getting the initial result:
$users = User::all();
它运行:
select * from `users`
之后,如果我们决定需要所有这些用户的相关 comments ,我们可以在事后立即加载它们:
$users = $users->load('comments');
which runs the 2nd query:
select * from `comments` where `comments`.`user_id` in (1, 2, 3, 4, 5)
...and we end up with the same result, just split into two steps. Again, we can call $users->comments->first()->body
to get to the related model for any item.
为什么使用load()
对with()
?load()
提供了一个选项,可以在以后根据一些动态条件决定是否需要运行第二个查询.但是,如果毫无疑问您需要访问所有相关项目,请使用with()
.
这两种方法的替代方法是循环初始结果集,并 for each 项目查询hasMany()
个关系.最终将运行n+1个查询,在本例中为6个.即时加载,不管是在with()
之前完成的,还是在load()
之后完成的,只运行2个查询.