laravel adjacency list - get subquery exists depth

163 Views Asked by At

rootCategory is HasOne relation:

public function rootCategory()
{
    return $this->hasOne(PartnerCategory::class, 'partner_id', 'id')->where('partner_category_main', 1);
}

then:

$categories = Partner::restaurants()->with('rootCategory')->get()->pluck('rootCategory')

then I need to know if rootCategory has childs with depth >1 and doing in CategoryResource:

$this->descendants()->whereDepth('>', 1)->exists()

but it making much more queries. How I can to query this same time with rootCategory relation?

I tried with(['rootCategory' => function($q) {return $q->descendants();}]) but it not working

1

There are 1 best solutions below

2
rozsazoltan On

Count SubQuery - WhereCount

You can get subquery row count with the "whereCount" function.

https://laravel.com/docs/10.x/eloquent-relationships#counting-related-models

Example with your code:

$categories =
  Partner::restaurants()
    ->withCount('rootCategory', function (Builder $query) {
       $query->descendants()->whereDepth('>', 1)->exists();
    })
    ->get()
    ->pluck('rootCategory');