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个查询.

Laravel相关问答推荐

Uncaught ReferenceError:未定义require[Shopify PHP React Browser问题]

Laravel:通过数据透视表数据限制多对多Eager 加载

如何解决此 Backblaze B2 S3 兼容 API 错误?

Ziggy 路由默认为查询字符串

Laravel 9 如何将 url 中的参数从一个控制器传递到另一个控制器?

如何通过单击进入 vs 代码中的类

用 laravel 表单确认删除?

Array_unique 上一个 laravel Eloquent的集合

Eloquent - 更新集合中的所有模型

Laravel 全部返回 ID 变为 0

验证匹配字符串

Laravel:命令未找到

在 Laravel 应用程序中在哪里指定应用程序版本?

Laravel 5.4 - Mix - 如何运行浏览器实时重新加载

如何在 Laravel 中使用补丁请求?

在 laravel 中删除排队的作业(job)

在 Laravel 中翻译特定语言

使用迁移更改表 Laravel 5

Laravel Mix:更新 Node.js 依赖项

laravel中的动态网址?