问题描述
我必须获取特定父节点的所有左节点和右节点。这是我的数据库表结构。
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());
我试图从父节点循环到它的节点,但是看起来越深,花费的时间就越长。 有没有更好的遍历树的方法?
解决方法
我建议使用已经创建并经过测试的程序包。
我也可以推荐此软件包用于嵌套树:https://github.com/lazychaser/laravel-nestedset