You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel递归分类查询:如何将父类及子类路径显示在同一行?

Laravel分类完整路径查询实现

修改递归方法生成完整路径

原来的递归方法仅存储分类名称,我们需要调整逻辑,在递归过程中拼接父级到当前分类的完整路径:

public static function getCategories($categories, &$result, $parent_id = 0, $currentPath = '')
{
    $cats = $categories->filter(function ($item) use ($parent_id) {
        return $item->parent_id == $parent_id;
    });

    foreach ($cats as $cat) {
        // 拼接当前分类的完整路径
        $fullPath = $currentPath ? $currentPath . ' -> ' . $cat->name : $cat->name;
        // 将完整路径存入结果,键为分类ID
        $result[$cat->id] = $fullPath;
        // 递归处理子分类,传递当前完整路径
        self::getCategories($categories, $result, $cat->id, $fullPath);
    }

    return $result;
}

public static function index()
{
    $categories = PropertyCategory::select('id', 'parent_id', 'name')->get();
    $result = [];
    $categoryPaths = self::getCategories($categories, $result);
    // 将结果传递到视图
    return view('categories.index', compact('categoryPaths'));
}

视图层渲染布局

在对应的Blade视图文件(比如resources/views/categories/index.blade.php)中,循环遍历分类路径数组,生成你需要的复选框布局:

@foreach($categoryPaths as $id => $path)
<div>
    <input type="checkbox" name="categories[]" id="category-{{ $id }}" value="{{ $id }}" />
    <label for="category-{{ $id }}">{{ $path }}</label>
</div>
@endforeach

说明

  • 递归时通过$currentPath参数传递已拼接的父级路径,每次子分类都会基于父路径生成自己的完整路径
  • 最终$categoryPaths数组的键是分类ID,值是从顶级父分类到当前分类的完整路径字符串
  • 视图中使用分类ID作为复选框的id和for属性,避免重复冲突

内容的提问来源于stack exchange,提问作者Fzol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 10:04:58