【问题标题】:How to Eager-load multiple nested sub-relations in Laravel 5?如何在 Laravel 5 中急切加载多个嵌套子关系?
【发布时间】:2017-12-16 06:10:13
【问题描述】:

我有一个失败的复杂数据结构:

Event: top-level object
|-Streams: events can contain multiple streams of information / data capture
  |-Datacapture: each stream can have up to 4 datacapture records
  |-Overlay: each stream can have many overlays
  | |-Frames: each overlay can have many frames
  |-Background: each stream can have many backgrounds
  | |-Frames: each background can have many frames
  |-Experiences: each stream can have up to 6 experiences
    |-Selectors: each experience can have many selectors
      |-Filters: each selector can have one filter
      |-Props: each selector can have one prop (whether it has a filter or no)
      | |-Frames: each prop can have many frames
      |-Overlay: each selector can have one overlay
      | |-Frames: each overlay can have many frames
      |-Background: each selector can have one background
      | |-Frames: each background can have many frames

这只是拼图的一部分——有更多的对象附加到体验和流中,但我认为这给出了要点。

理想情况下,我希望创建一个单一的即时加载查询,该查询可以加载并返回完整的 EVENT 集合及其所有组成部分。

我知道我可以用with(['blah','plop']) 加载多个关系,我可以用with('blah.plop') 加载嵌套关系,我什至可以用with(['blah.plop','blah.somethingelse']) 加载多个嵌套关系,但是我的情况显然更复杂。

我想避免像

那样单独加载每个“子关系”
$event = event::with([
    'streams.datacaptures',
    'streams.overlay.frames',
    'streams.background.frames',
    'streams.experiences.selectors.filters',
    'streams.experiences.selectors.props.frames',
    'streams.experiences.selectors.overlay.frames',
    'streams.experiences.selectors.background.frames'
    ])->find($eventcode);

我可以做一些更整洁/更清洁的事情吗?

【问题讨论】:

  • 事实证明,至少在 Laravel 5 中,据我所知,这些被智能组合并且元素不会重复。

标签: php laravel eloquent eager-loading


【解决方案1】:

好吧,我不知道这对你来说是否更整洁/更干净..

与您的模型事件的急切负载关系

protected $with = ['streams'];

另一个也一样 .. 有流

protected $with = ['datacaptures','overlay','background','experiences'];

在背景和叠加中

protected $with = ['frames'];

等等..

默认情况下,这将调用模型具有的所有关系.. 但缺点是即使您不需要它也会急切加载..

所以你只需要

$event = event::find($eventcode);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2016-06-06
    • 2019-07-25
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 2015-08-16
    相关资源
    最近更新 更多