Laravel Eloquent:渴望加载多个嵌套关系

时间:2016-02-18 19:30:18

标签: laravel eloquent eager-loading

laravel说:

$books = App\Book::with('author.contacts')->get();

我需要的是这样的东西

$books = App\Book::with('author[contacts,publishers]')->get();

我们渴望在关系中加载多个关系。

这可能吗?

3 个答案:

答案 0 :(得分:69)

你可以做到

 $books = App\Book::with('author.contacts','author.publishers')->get();

答案 1 :(得分:4)

所以,现在你可以试试

$books = App\Book::with(['author' => function($author){
     $author->with(['contacts', 'publishers'])->get();
}])->get();

答案 2 :(得分:3)

关于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' => function ($query) {
                                          $query->where('title', 'like', '%first%');
                                     }, 'email', 'author.contacts', 'author.publishers'])->get();