laravel渴望加载与自己的关系

问题描述 投票:0回答:1

我有这样的模型,它与自身有关系

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>

我该怎么做?

php laravel eloquent eager-loading laravel-5.8
1个回答
0
投票

您应该使用whereHas()功能。看看official documentation

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

因此,在您的情况下,您必须按以下方式更改方法:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.