### ***一.關聯預載入***
1.在普通的關聯查詢下:我們循環數據列表會執行n+1次SQL查詢
$list = UserModel::all(\[1,2,3\]);
foreach($list as $user){
dump($user->profile);
}
***2.上面繼續采用一對一的構建方式,打開trace調試工具,會得到四次查詢;***
***3.如果采用關聯預載入的方式,將會減手到兩次,也就是起步一次,循環一次***
$list = UserModel::with('profile')->all(\[1,2,3\]);
foreach($list as $user){
dump($user->profile)
}
***with()是IN方式的查詢,如果想使用JOIN查詢,可以使用withJoin();***
UserModel::withJoin('profile')->all(\[1,2,3\]);
在使用JOIN查詢方案下,限定字段,可以使用withField()方法來進行
$list = UserModel::withJoin(\['profile'=>function($query){
$query->withField('hobby');
}\])->all(\[1,2,3\]);
***關聯預載入還提供了一個延遲預載入,就是先執行all()再load()載入,***
這個也就是說,在載入前,去延遲一下,然后在延遲的時間中還可以去做一些其他的操作
$list = UserModel::all(\[1,2,3\]);//先執行all查詢
//可以做一些操作
$list->**load**('profile');//**延遲預加載**
foreach($list as $user){
dump($user->profile);
}