Laravel技巧:使用load、with預加載 區別


1、使用load

  1. $posts = Post::all();
  2. $posts->load( 'user');

2、使用with

$posts = Post::with('user')->all();

懶加載是什么意思呢?

兩張表,目錄表和教材表。多個教材屬於一個目錄,那么利用懶加載,你就可以通過先把目錄讀出來,然后把這些與目錄有關的教材一下子讀出來完。這樣進行數據庫讀取的次數就少了。

所以我從國外的一個網站上搬來了with和load的用法,大家自行領悟吧。

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” here means that we’re associating all the related models for a particular result set using just one query, as opposed to having to run n queries, where n is the number of items in the initial set.

Eager loading using with()

If we eager load using with(), for example:

$users = User::with('comments')->get(); 

if we have 5 users, the following two queries get run immediately:

select * from `users` select * from `comments` where `comments`.`user_id` in (1, 2, 3, 4, 5) 

…and we end up with a collection of models that have the comments attached to the user model, so we can do something like $users->comments->first()->body.

“Lazy” eager loading using load()

In this approach, we can separate the two queries, first by getting the initial result:

$users = User::all(); 

which runs:

select * from `users` 

And later, if we decide(based on some condition) that we need the related comments for all these users, we can eager load them after the fact:

if($someCondition){  $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.

Conclusion

When to use load() or with()?

load() gives you the option of deciding later, based on some dynamic condition, whether or not you need to run the 2nd query.

If, however, there’s no question that you’ll need to access all the related items, use with().

 



先說說 關聯查詢:我們在 Model 類里定義的關聯,我們不一定在第一次查詢就全部查出來,我們可以在需要的時候再去查詢 ,使用 load 方法,可以實現這個目標,
但是這個 load 只是針對單個 model 對象的
如果我們 Model::xxx()->xx() 鏈式操作最后是 get(),我們得到的結果將會是一個 Collection 實例,
最后調用的方法是 first() 或其他類似的 firstOrFail() 的時候,返回的才是一個 Model 實例
也就是說 load 方法只針對 Model 實例。如下:

總結:with 一步等於執行了兩步,
load 分開執行兩步

參考:https://www.cnblogs.com/cjjjj/p/9839725.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM