Okay i am working on a laravel 5.5 project.
We have a user table and in this user table we have a parent field. The parent declines the parent relationship of this object.
So each user can have 1 parent but a user can have multiple children.
public function parent()
{
return $this->belongsTo(User::class, 'parent_id', 'id');
}
public function children()
{
return $this->hasMany(User::class, 'parent_id', 'id');
}
What i want to achieve is. I need to count 5 levels deep how many children a user has.
so i want something like:
Level 1: 585 Level 2: 1539 Level 3: 3294 Level 4: 4949 Level 5: 15939
Without loading the actual objects for sure, as it would kill the page performance.
How can i achieve this with laravel? Heres what i tried, but it loads all the subchildren in a collection.
$sum = User::with('parent')->where('id','=', $user->id)->get();
Somebody can help me out with that?
EDIT:
Just to be more specific:
Lets say User A is parent of B and C
B is parent of D, E, F C has no children.
The correct output should be:
Level 1: 2 Level 2: 3 (as C has no children)
Hope that makes it more clearer