层次树遍历Laravel / PHP

问题描述

我必须获取特定父节点的所有左节点和右节点。这是我的数据库表结构。

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...