【问题标题】:Laravel Eloquent: eager loading of multiple nested relationshipsLaravel Eloquent:渴望加载多个嵌套关系
【发布时间】:2016-05-31 03:58:41
【问题描述】:

laravel 是怎么说的:

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

我需要的是这样的

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

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

这可能吗?

【问题讨论】:

    标签: laravel eloquent eager-loading


    【解决方案1】:

    你可以的

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

    【讨论】:

    • 只是添加,它当然也会获取相应的作者数据。
    • 跟进:我有一个更复杂的模型,想返回一个集合,但像原始海报一样,希望我可以在较低的子级别使用多个嵌套关系,例如$event = event::with(['streams.experiences.selectors.['digitalprops.frames','filters']','streams.datacaptures'])->find($eventcode);
    • @Todd 你如何在 Laravel 中执行这段代码? $event = event::with(['streams.experiences.selectors.['digitalprops.frames','filters']','streams.datacaptures'])->find($eventcode);。它不应该工作......!
    • 对@tisuchi -- 我说过我希望我可以...抱歉造成混乱。
    • 作者是表名还是什么?
    【解决方案2】:

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

    【讨论】:

    • 这是如何高效加载的最佳概述!
    • 这看起来太棒了!感谢您的意见!
    【解决方案3】:

    那么,现在你可以试试

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

    【讨论】:

    • 我认为 ->get() 在闭包中根本不需要
    【解决方案4】:

    当急切加载嵌套关系并且我们只想选择一些列而不是全部使用 relationship:id,name 时,始终包含嵌套模型的外键,否则它们根本不会加载。

    例如,我们有 ordersidentitiesaddresses

    这不会加载地址:

    User::orders()
        ->with('identity:id,name', 'identity.address:id,street')
    

    这将加载地址,因为我们提供了 address_id 外键:

    User::orders()
        ->with('identity:id,address_id,name', 'identity.address:id,street')
    

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 2016-08-18
      • 2014-02-24
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 2015-05-16
      • 2019-06-19
      相关资源
      最近更新 更多