EnikiBeniki
EnikiBeniki

Reputation: 981

How to get nested count via Eloquent?

I have simple nested tree model:

Page table

id
owner_id
title

Any page can have similar Pages related by key owner_id and refers to the same table records.

How to get some page with count of the nested pages by id through Eloquent?

In a native SQL i can do something like this:

SELECT pages.*, count(subPage.id) AS childCount
FROM pages AS page
LEFT JOIN pages AS subPage ON (subPage .owner_id = page.id)
....

Something like this:

$page->childsCount will return count of related sub pages.

Upvotes: 0

Views: 2450

Answers (4)

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

Assuming that you already have pages() relationship defined, you can use withCount() method:

Page::withCount('pages')->first();

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.

Upvotes: 3

Raj Rajput
Raj Rajput

Reputation: 21

I found the easiest way to count nested hasMany relationship counts in Laravel. Suppose we have three models with has many and nested hasMany relationships:

Category Model:

public function subCategories()
    {
        return $this->hasMany('App\Models\Subcategory');
    }

Subcategory Model

public function products()
    {
        return $this->hasMany('App\Models\Product');
    }


$categories = $this->categoryRepository
    ->with([
        'subCategories' => function ($query) {
            $query->withCount('products');
        }])
    ->whereIn("id", $categories_id)
    ->orderBy('id', 'desc')->get();

You will get the product count using all these three steps.

Upvotes: 2

EnikiBeniki
EnikiBeniki

Reputation: 981

Was solved in this way

in Page Model

...

    protected $childCount = 0;


    public function pages()
    {
        return $this->hasMany(Page::class, 'owner_id');
    }

    public function childCount()
    {
        return $this->childCount ? $this->childCount : $this->pages()->select('id')->count();
    }
...

And we get access to sub pages count via $page->childCount() model method.

Upvotes: 0

Bara' ayyash
Bara' ayyash

Reputation: 1935

By having a relation between Page and Owner you can do this:

$page->owner->pages->count();

Upvotes: 0

Related Questions