Laravel Eloquent: eager loading of multiple nested relationships

家住魔仙堡 提交于 2019-11-29 00:21:56

问题


What laravel says:

$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?


回答1:


You can do

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



回答2:


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

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


来源:https://stackoverflow.com/questions/35490728/laravel-eloquent-eager-loading-of-multiple-nested-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!