當(dāng)通過屬性訪問 Eloquent 關(guān)聯(lián)時(shí),該關(guān)聯(lián)數(shù)據(jù)會(huì)被「延遲加載」乒躺。意味著該關(guān)聯(lián)數(shù)據(jù)只有在你使用屬性訪問它時(shí)才會(huì)被加載。
例如
$books = App\Book::all();
foreach ($books as $book) {
echo $book->author->name;
}
這樣將執(zhí)行N+1步查詢:
1次:查詢出所有書N本低缩,
N次:每本書查詢一次作者
預(yù)加載的話
$books = App\Book::with('author')->get();
foreach ($books as $book) {
echo $book->author->name;
}
只執(zhí)行兩部
select * from books
select * from authors where id in (1, 2, 3, 4, 5, ...)
預(yù)加載的方式
加載多個(gè)關(guān)聯(lián)
$books = App\Book::with('author', 'publisher')->get();
加載嵌套關(guān)聯(lián)
$books = App\Book::with('author.contacts')->get();
篩選加載結(jié)果
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
延遲預(yù)加載
$books = App\Book::all();
if ($someCondition) {
$books->load(['author' => function ($query) {
$query->orderBy('published_date', 'asc');
}]);
}