首页 文章

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

提问于
浏览
29

什么laravel说:

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

我需要的是这样的事情

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

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

这可能吗?

2 回答

  • 0

    你可以做

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

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

相关问题