I have to fetch all left and right nodes of a specific parent node. This is my database table structure.
Schema::create('user', function (Blueprint $table) {
$table->id();
$table->string('code')->unique();
$table->string('parent_code');
$table->enum('position', ['left', 'right', 'root']);
});
$users= User::where('parent_code', $account->code)->where('position', 'left')->get();
$collect = new Collection();
do {
foreach ($users as $item) {
$level = User::where('parent_code', $item->code)->get();
foreach ($level as $lvlitem) {
$collect->push($lvlitem);
}
}
$users = $collect;
} while (!$users->isEmpty());
I tried to loop from my parent to its nodes but it seems like the deeper it goes the longer it will take. Is there a better way to traverse the tree?
I would suggest to use already created and tested package for things like that.
And i also can recommend this package for nested tree: https://github.com/lazychaser/laravel-nestedset