laravel eager loading for self relation
Asked Answered
C

2

0

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?

Chloroform answered 30/9, 2019 at 7:43 Comment(1)
It's not very clear what you're trying to achieve... Can you add also the code where you use the with() method?Massacre
M
0

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.

Massacre answered 30/9, 2019 at 12:0 Comment(0)
R
0

This is an example for you. This might help to solve your problem. I have Structure Model which contain organizational structure of a company.

In my StructureController.php

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

In my Structure.php, I add with() at the relationship for eager loading.

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

And, if you you check with this package here , it won't show any warning.

Reference : check this website here

Readjustment answered 3/1, 2022 at 8:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.