Can you help me with the user hierarchy?

Hi, I am trying to create a hierarchy for users. Each user can have a referrer (parent), while in the RelationManager I need to display all the children of the given user. Not only the direct ones, but also the recursive ones.

For example, I have the following users in my database:
[
    ['id' => 1, 'name' => 'John', 'refferer_id' => null],
    ['id' => 2, 'name' => 'Jane', 'refferer_id' => 1], // direct child
    ['id' => 3, 'name' => 'Baby', 'refferer_id' => 2], // recursive child
]


So I created these relationships for User model:
public function referrer()
{
    return $this->belongsTo(User::class, 'referrer_id');
}

public function parents()
{
    return $this->belongsTo(User::class, 'referrer_id')
        ->with('referrer');
}

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


I also created RelationManager for children:
class ChildrenRelationManager extends RelationManager
{
    protected static string $relationship = 'children';
}


Finally, my problem is, that when I open John resource, I only see Jane as children, but I want to see also Baby.
Can anyone help me, please?

A better example would be a category that has parent and child categories, but the principle is the same.
Was this page helpful?