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

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)

  • 只需添加,它将获取相应的作者数据以及课程. (4认同)

小智 11

所以,现在你可以尝试

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

  • 我认为闭包中根本不需要 `->get()` (2认同)

Eli*_*noo 9

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)

  • 这是如何有效地预加载的最好概述! (3认同)
  • 这看起来棒极了!感谢您的输入! (3认同)

Was*_*ash 5

从 Laravel 9 开始,最简洁的方式是嵌套数组:

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

参考