【问题标题】:laravel eager loading for self relationlaravel 渴望加载自我关系
【发布时间】:2019-09-30 07:43:20
【问题描述】:

我有像这样与自身相关的模型

public function children() {
        return $this->hasMany(AppointmentPart::class,'parent_id');
}

我想急切加载此模型的查询,但因为每一行都可以有子 with() 方法对我不起作用

$parts = AppointmentPart::whereParentId(0)->with('children')->get();

我的刀:

<ul id="treeData">
                     @foreach($parts as $part)
                          <li id="{{ $part->id }}"
                                        @if(!empty($part->children)) class="folder" @endif>
                                        {{ $part->title }}
                                        @if(!empty($part->children))
                                            @include('appointment::admin.appointment.layout._part_child', array('parts' => $part->children))
                                        @endif
                      </li>
                  @endforeach
</ul>

_part_child 的内容:

<ul>
    @foreach($parts as $part)
        <li id="{{ $part->id }}" @if(!empty($part->children)) class="folder" @endif>
            {{ $part->title }}
            @include('appointment::admin.appointment.layout._part_child',['parts'=>$part->children])
        </li>
    @endforeach
</ul>

我该怎么做?

【问题讨论】:

  • 不太清楚您要实现的目标...您能否在使用with() 方法的地方也添加代码?

标签: php laravel eloquent eager-loading laravel-5.8


【解决方案1】:

您应该使用whereHas() 函数。看看official documentation

如果您需要更强大的功能,您可以使用 whereHas 和 orWhereHas 方法在您的 has 查询中添加“where”条件。这些方法允许您将自定义约束添加到关系约束 [...]

所以在你的情况下,你必须改变你的方法如下:

$parts = AppointmentPart::with('children')->whereHas('children', function($query) use ($parent_id) {
    $query->where('parent_id', '=', $parent_id);
})->get();

您还可以创建local scope 以创建可重用的查询语句。

【讨论】:

    【解决方案2】:

    这是给你的一个例子。这可能有助于解决您的问题。我有包含公司组织结构的结构模型。

    在我的 StructureController.php 中

    public function index()
        {
            $parentStructures = Structure::where('parent_id', 0)->get();
            return view('structure.structureTreeview', compact('parentStructures'));
        }
    

    在我的 Structure.php 中,我在关系中添加 with() 以进行预加载。

    public function children()
        {
            return $this->hasMany(Structure::class, 'parent_id')->with('children');
        }
    

    而且,如果你检查这个包 here ,它不会显示任何警告。

    参考:查看本站here

    【讨论】:

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