Here's my database structure
id | parent_id | depth | position
---------------------------------
2 | 1 | 1 | left
---------------------------------
3 | 1 | 1 | right
---------------------------------
4 | 2 | 2 | left
---------------------------------
5 | 3 | 2 | left
---------------------------------
6 | 2 | 3 | right
---------------------------------
7 | 4 | 4 | right
---------------------------------
I wrote a recursive function to get the total left or right nodes of a particular "id" on a particular depth, but the it is too heavy as the depth can go up to 300+.
For example i want to get how many child nodes on the left section does id 2 has, in this case 2, 4 and 7 is on the left section of node 2, and on particular depth 4 there is only 1 on the left section.
Is there a better way to get all the left section node count on a particular depth.
protected function rec($parent_id, $current_level, $requested_level, $created_at) {
$query = DB::select("select username, id, depth, DATE(created_at) as created_at from users where parent_id = $parent_id");
if ($current_level == $requested_level) {
$this->result1++;
return;
}
else {
if(!empty($query)){
foreach($query as $row){
$this->rec($row->id, $row->depth, $requested_level, $row->created_at);
}
}
else{
return;
}
}
}