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
]
[
['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');
}
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';
}
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.
2 Replies
Trauma Zombie
Trauma Zombie14mo ago
I used this package and it works just fine. https://github.com/staudenmeir/laravel-adjacency-list
GitHub
GitHub - staudenmeir/laravel-adjacency-list: Recursive Laravel Eloq...
Recursive Laravel Eloquent relationships with CTEs - GitHub - staudenmeir/laravel-adjacency-list: Recursive Laravel Eloquent relationships with CTEs
Clay Bitner
Clay Bitner11mo ago
I'm facing the same issue. How did you end up integrating it and adding it to the RelationManager?