【发布时间】:2016-05-31 03:58:41
【问题描述】:
laravel 是怎么说的:
$books = App\Book::with('author.contacts')->get();
我需要的是这样的
$books = App\Book::with('author[contacts,publishers]')->get();
我们渴望在一个关系中加载多个关系。
这可能吗?
【问题讨论】:
标签: laravel eloquent eager-loading
laravel 是怎么说的:
$books = App\Book::with('author.contacts')->get();
我需要的是这样的
$books = App\Book::with('author[contacts,publishers]')->get();
我们渴望在一个关系中加载多个关系。
这可能吗?
【问题讨论】:
标签: laravel eloquent eager-loading
你可以的
$books = App\Book::with('author.contacts','author.publishers')->get();
【讨论】:
$event = event::with(['streams.experiences.selectors.['digitalprops.frames','filters']','streams.datacaptures'])->find($eventcode);
$event = event::with(['streams.experiences.selectors.['digitalprops.frames','filters']','streams.datacaptures'])->find($eventcode);。它不应该工作......!
eager loading 上的 Laravel 文档建议将关系列在数组中,如下所示:
$books = App\Book::with(['author.contacts', 'author.publishers'])->get();
您可以拥有任意数量的关系。您还可以为这样的关系指定应包含哪些列:
//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();
您还可以按如下方式添加约束:
$books = App\Book::with(['author: id, name, email', 'author.contacts' => function ($query) {
$query->where('address', 'like', '%city%');
}, 'author.publishers'])->get();
【讨论】:
那么,现在你可以试试
$books = App\Book::with(['author' => function($author){
$author->with(['contacts', 'publishers'])->get();
}])->get();
【讨论】:
->get() 在闭包中根本不需要
当急切加载嵌套关系并且我们只想选择一些列而不是全部使用 relationship:id,name 时,始终包含嵌套模型的外键,否则它们根本不会加载。
例如,我们有 orders 有 identities 有 addresses。
这不会加载地址:
User::orders()
->with('identity:id,name', 'identity.address:id,street')
这将加载地址,因为我们提供了 address_id 外键:
User::orders()
->with('identity:id,address_id,name', 'identity.address:id,street')
【讨论】: