thinkphp5 with的常用寫法


為何使用with
關聯查詢的預查詢載入功能,主要解決了N+1次查詢的問題,例如下面的查詢如果有3個記錄,會執行4次查詢:

舉個栗子:

$list = User::all([1,2,3]);
foreach($list as $user){
    //
獲取用戶關聯的
profile
模型數據
dump($user->profile);
}
1
2
3
4
5
6
7
8
如果使用關聯預查詢功能,對於一對一關聯來說,只有一次查詢,對於一對多關聯的話,就可以變成2次查詢,有效提高性能。

$list = User::with('profile')->select([1,2,3]);
foreach($list as $user){
    //
獲取用戶關聯的
profile
模型數據
dump($user->profile);
}
1
2
3
4
5
6
7
8
用/寫法
單個預載入
$list = User::with('profile')->select([1,2,3]);
1
這里載入的profile 最后查詢字段由你配置關聯關系時候設置的filed來定,當然也可以在配置關聯關系時不使用filed來指定,在with時指定的話,需要使用到閉包函數的方式指定
舉個栗子:

$list = User::with('profile' =>  function($query){
                $query->withField('id, name, status');
            })->select([1,2,3]);
1
2
3
多個關聯模型預載入
在查詢中經常會遇到需要預載入多個關聯模型的情況,舉個例子:

$list = User::with(['profile', 'info', 'order'])->select([1,2,3]);
1
多層關聯關系載入
在預載入中,最復雜的屬於多層預載入了,例如:user的order的product的brand
這個如果需要在user查詢時預載入,寫法如下:

$list = User::with(['profile', 'info', 'order' => ['product' => ['brand]]])->select([1,2,3]);
1
其實也簡單,就是使用數組嵌套方式去嵌套就好了。

最復雜寫法
就是在with 關聯模型時,使用了閉包查詢,而且還需要該模型下的其他關聯模型,這種寫法最復雜,直接上栗子:

$list = User::with('profile' =>  function($query){
                $query->withField('id, name, status')->with('test');
            })->select([1,2,3]);
1
2
3
注意閉包里面的with,因為這個query 是整個profile 對象,所以閉包里面就跟單獨查詢profile 一樣,該withField就 withField,該with 就with,還可以其他where 等操作。
————————————————
版權聲明:本文為CSDN博主「菜鳥沒翅膀」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/a437629292/article/details/78037468


免責聲明!

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



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