Laravel中构建无限层级分类树需避免N+1查询:先用with('children')预加载,再通过闭包递归、Accessor或WITH RECURSIVE原生查询组装树结构,各方法适用场景不同。

在Laravel中构建带有无限层级的分类树(如商品类目、文章栏目),需要从数据库中递归提取父子关系数据并组织成嵌套数组或集合,避免N+1查询导致性能骤降。
使用with()预加载解决N+1问题
先定义Category模型的父子关联关系,在app/Models/Category.php中添加以下方法:
public function children() { return $this->hasMany(Category::class, 'parent_id'); }
public function parent() { return $this->belongsTo(Category::class, 'parent_id'); }
在控制器中调用Category::with('children')->whereNull('parent_id')->get()即可一次性查出所有一级分类及其直接子分类。这一步必须做,否则后续递归遍历时每访问一个子集都会触发新SQL查询。
用递归函数组装完整树结构
方法一:在控制器中定义闭包递归函数
$buildTree = function ($categories, $parentId = null) use (&$buildTree) {
$tree = [];
foreach ($categories as $category) {
if ($category->parent_id == $parentId) {
$category->children = $buildTree($categories, $category->id);
$tree[] = $category;
}
}
return $tree;
};
$tree = $buildTree($categories);
注意:此方式要求$categories是Eloquent Collection而非Query Builder对象,且必须已加载全部数据(即不能用chunk或cursorPaginate)。
用Eloquent Accessor自动附加子级
在Category模型中添加accessor:
protected $appends = ['child_tree'];
public function getChildTreeAttribute() {
$children = $this->children;
return $children->map(function ($child) {
return $child->append('child_tree');
})->values();
}
Laravel Cloud(cloud.laravel.com)。此技能用于处理所有 Laravel Cloud 请求,包括搜索和读取数据。只要任务涉及 Laravel Cloud,即使用此技能。
调用时用Category::with('children')->whereNull('parent_id')->get()->makeHidden(['children'])获取纯树形结构。这种方法简洁,但【会强制递归展开全部层级,无法控制深度】,大数据量时内存易爆。
使用DB原生查询一次性获取带层级路径的结果
第一步:执行WITH RECURSIVE查询(MySQL 8.0+/PostgreSQL支持)
$sql = "WITH RECURSIVE category_tree AS (
SELECT id, name, parent_id, 1 as level
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.name, c.parent_id, ct.level + 1
FROM categories c
INNER JOIN category_tree ct ON c.parent_id = ct.id
)
SELECT * FROM category_tree ORDER BY level, id";
$flattened = DB::select($sql);
第二步:用PHP将扁平结果转为嵌套数组
$map = [];
$tree = [];
foreach ($flattened as $row) {
$map[$row->id] = (array)$row + ['children' => []];
if ($row->parent_id === null) {
$tree[] = &$map[$row->id];
} else {
$map[$row->parent_id]['children'][] = &$map[$row->id];
}
}
第三步:释放引用避免重复数据污染
unset($map);










