Laravel Eloquent:急切加载多个嵌套关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35490728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:17:03  来源:igfitidea点击:

Laravel Eloquent: eager loading of multiple nested relationships

laraveleloquenteager-loading

提问by DrivingInsanee

What laravel says:

什么 laravel 说:

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

What I need is something like this

我需要的是这样的

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

where we eager load multiple relationships within a relationship.

我们急切地加载关系中的多个关系。

Is this possible?

这可能吗?

回答by oseintow

You can do

你可以做

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

回答by Elisha Senoo

Laravel documentation on eager loadingrecommends listing the relationships in an array as follows:

Laravel 上关于预先加载的文档建议按如下方式列出数组中的关系:

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

You can have as many relationships as desired. You can also specify which columns should be included for a relationship like this:

您可以根据需要拥有任意数量的关系。您还可以指定应为关系包含哪些列,如下所示:

//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();

You may also add constrains as follows:

您还可以按如下方式添加约束:

$books = App\Book::with(['author: id, name, email' => function ($query) {
                                          $query->where('title', 'like', '%first%');
                                     }, 'email', 'author.contacts', 'author.publishers'])->get();