如何在Laravel 5中加载多个嵌套的子关系?

时间:2017-07-12 01:58:35

标签: php laravel eloquent eager-loading

我有一个非常复杂的数据结构:

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

我能做些更整洁/更清洁的事吗?

1 个答案:

答案 0 :(得分:1)

我不知道这对你来说是否更整洁/更清洁..

与模型事件的紧急负载关系

protected $with = ['streams'];

同样是另一个..用流

protected $with = ['datacaptures','overlay','background','experiences'];
背景和叠加

protected $with = ['frames'];

等等。

  

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

所以你必须

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