如何解决层次树遍历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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。