0 && !isset($visited[$currentId])) { $visited[$currentId] = true; $dept = SystemDept::find($currentId); if (!$dept) { return null; } $parentId = (int) ($dept->parent_id ?? 0); if ($parentId === 0) { return $currentId; } $currentId = $parentId; } return $currentId > 0 ? $currentId : null; } Db::transaction(function () { $users = SystemUser::where('dept_id', '>', 0)->select(); foreach ($users as $user) { $deptId = (int) $user->dept_id; $rootId = getRootDeptId($deptId); if ($rootId !== null && $rootId !== $deptId) { SystemUser::where('id', $user->id)->update(['dept_id' => $rootId]); echo "用户 {$user->id} dept_id {$deptId} -> {$rootId}\n"; } } $childIds = SystemDept::where('parent_id', '>', 0)->column('id'); if (!empty($childIds)) { SystemDept::destroy($childIds); echo '已删除子渠道: ' . implode(',', $childIds) . "\n"; } SystemDept::where('id', '>', 0)->update(['parent_id' => 0, 'level' => '0']); echo "渠道扁平化完成\n"; });