I would search the database and mount an array objects with the entire network of users from the last parent_id. Example:
id | parent_id | nome | email
Create output in this format:
[
(int) 0 => {
id => 1,
parent_id => null
nome => nome
},
(int) 1 => {
id => 2,
parent_id => 1
nome => nome
},
(int) 2 => {
id => 3,
parent_id => 1
nome => nome
},
(int) 3 => {
id => 4,
parent_id => 3
nome => nome
},
(int) 4 => {
id => 5,
parent_id => 4
nome => nome
}
]
I tried it that way
public function getArvore($id, $level){
$users = $this->find()
->where(['parent_id' => $id]);
$arvore[$level] = $users->toArray();
if($users->count() > 0){
foreach($users as $key => $user){
$level++;
$arvore[$level] = $this->getArvore($user->id, $level);
}
}
return isset($arvore) ? array_filter($arvore) : null;
}
Output
[
(int) 0 => [
(int) 0 => object(App\Model\Entity\User) {
'id' => (int) 85,
'parent_id' => (int) 71,
'nome' => 'Teste'
},
(int) 1 => object(App\Model\Entity\User) {
'id' => (int) 153807,
'parent_id' => (int) 71,
'nome' => 'Teste'
},
(int) 2 => object(App\Model\Entity\User) {
'id' => (int) 153808,
'parent_id' => (int) 71,
'nome' => 'Teste'
},
(int) 3 => object(App\Model\Entity\User) {
'id' => (int) 163387,
'parent_id' => (int) 71,
'nome' => 'Teste'
}
],
(int) 2 => [
(int) 2 => [
(int) 0 => object(App\Model\Entity\User) {
'id' => (int) 185251,
'parent_id' => (int) 153807,
'nome' => 'Teste'
}
]
]
]
There was little left to stay the way I need it.