0
votes

I have the model that has relation to itself like this

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

I want to eager loading for queries for this model but because every row can have child with() method doesn't work for me

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

my blade:

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

content of _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>

how can I do this?

1
It's not very clear what you're trying to achieve... Can you add also the code where you use the with() method? - IlGala

1 Answers

0
votes

You should use a whereHas() function. Have a look at the official documentation.

If you need even more power, you may use the whereHas and orWhereHas methods to put "where" conditions on your has queries. These methods allow you to add customized constraints to a relationship constraint [...]

So in your case you have to change your method as follows:

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

you can also create a local scope in order to create a reusable query statement.