Dri*_*nee 38 eager-loading laravel eloquent
什么laravel说:
$books = App\Book::with('author.contacts')->get();
Run Code Online (Sandbox Code Playgroud)
我需要的是这样的事情
$books = App\Book::with('author[contacts,publishers]')->get();
Run Code Online (Sandbox Code Playgroud)
我们渴望在关系中加载多个关系.
这可能吗?
ose*_*tow 84
你可以做
$books = App\Book::with('author.contacts','author.publishers')->get();
Run Code Online (Sandbox Code Playgroud)
小智 11
所以,现在你可以尝试
$books = App\Book::with(['author' => function($author){
$author->with(['contacts', 'publishers'])->get();
}])->get();
Run Code Online (Sandbox Code Playgroud)
Laravel有关急切加载的文档建议将数组中的关系列出如下:
$books = App\Book::with(['author.contacts', 'author.publishers'])->get();
Run Code Online (Sandbox Code Playgroud)
您可以根据需要建立多个关系。您还可以指定如下所示的关系应包括哪些列:
//only id, name and email will be returned for author
//id must always be included
$books = App\Book::with(['author: id, name, email', 'author.contacts', 'author.publishers'])->get();
Run Code Online (Sandbox Code Playgroud)
您还可以如下添加约束:
$books = App\Book::with(['author: id, name, email' => function ($query) {
$query->where('title', 'like', '%first%');
}, 'email', 'author.contacts', 'author.publishers'])->get();
Run Code Online (Sandbox Code Playgroud)
从 Laravel 9 开始,最简洁的方式是嵌套数组:
$books = App\Book::with(['author' => [
'contacts',
'publishers'
])->get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22793 次 |
| 最近记录: |