Php 拉威尔对自我关系的渴望
我有一个模型,它与自身有这样的关系Php 拉威尔对自我关系的渴望,php,laravel,eloquent,eager-loading,laravel-5.8,Php,Laravel,Eloquent,Eager Loading,Laravel 5.8,我有一个模型,它与自身有这样的关系 public function children() { return $this->hasMany(AppointmentPart::class,'parent_id'); } 我希望加载此模型的查询,但因为每一行都可以有with()方法的子对象,所以我无法使用该方法 $parts = AppointmentPart::whereParentId(0)->with('children')->get(); 我的刀片: &l
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>
@foreach($parts作为$part)
- children))class=“folder”@endif>
{{$part->title}
@如果(!空($part->children))
@包括('appointment::admin.appointment.layout.\u part\u child',数组('parts'=>$part->children))
@恩迪夫
@endforeach
_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>
@foreach($parts作为$part)
- children))class=“folder”@endif>
{{$part->title}
@包括('appointment::admin.appointment.layout.\u part\u child',['parts'=>$part->children])
@endforeach
如何执行此操作?您应该使用
whereHas()
函数。看一看这张照片
如果您需要更多的功能,您可以使用whereHas和orWhereHas方法在has查询中设置“where”条件。这些方法允许您将自定义约束添加到关系约束[…]
因此,在您的情况下,您必须更改您的方法,如下所示:
$parts = AppointmentPart::with('children')->whereHas('children', function($query) use ($parent_id) {
$query->where('parent_id', '=', $parent_id);
})->get();
您还可以创建一个查询语句,以便创建一个可重用的查询语句。不太清楚您想要实现什么。。。您是否可以在使用
with()
方法的地方添加代码?