当通过属性访问 Eloquent 关联时,该关联数据会被「延迟加载」。意味着该关联数据只有在你使用属性访问它时才会被加载。
例如
$books = App\Book::all();
foreach ($books as $book) {
echo $book->author->name;
}
这样将执行N+1步查询:
1次:查询出所有书N本,
N次:每本书查询一次作者
预加载的话
$books = App\Book::with('author')->get();
foreach ($books as $book) {
echo $book->author->name;
}
只执行两部
select * from books
select * from authors where id in (1, 2, 3, 4, 5, ...)
预加载的方式
加载多个关联
$books = App\Book::with('author', 'publisher')->get();
加载嵌套关联
$books = App\Book::with('author.contacts')->get();
筛选加载结果
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
延迟预加载
$books = App\Book::all();
if ($someCondition) {
$books->load(['author' => function ($query) {
$query->orderBy('published_date', 'asc');
}]);
}