分层树形分类全路径并排输出到表格的实现及递归函数修复
解决方案
你原有递归函数的问题是遍历第一个分类就直接return终止执行,既没有收集所有层级的分类信息,也没有拼接路径,所以无法得到预期结果。按以下步骤修改即可:
1. 调整Category模型关联
确保模型内的子分类关联定义正确:
// app/Models/Category.php public function subcategory() { return $this->hasMany(Category::class, 'parent_id', 'id'); }
2. 控制器修改递归方法
在控制器中新增属性存储全路径数据,重写递归逻辑拼接路径:
// 控制器内新增属性存储所有分类的全路径 private $categoryPaths = []; /** * 递归生成分类全路径 * @param $categories 分类集合 * @param string $parentPath 父级全路径 */ public function generateCategoryPaths($categories, string $parentPath = '') { foreach ($categories as $category) { // 拼接当前分类的完整路径 $currentPath = $parentPath ? $parentPath . ' - ' . $category->name : $category->name; // 存入结果数组,保留id供编辑操作使用 $this->categoryPaths[] = [ 'id' => $category->id, 'full_path' => $currentPath ]; // 存在子分类则递归调用 if ($category->subcategory->isNotEmpty()) { $this->generateCategoryPaths($category->subcategory, $currentPath); } } }
3. 控制器index方法调用逻辑
查询顶级分类后调用递归方法,把结果传给模板:
public function index() { // 预加载子分类关联,避免N+1查询问题 $topCategories = Category::whereNull('parent_id')->with('subcategory')->get(); $this->generateCategoryPaths($topCategories); return view('index', [ 'categories' => $this->categoryPaths ]); }
4. Blade模板渲染表格
直接遍历传递的分类路径数据渲染即可:
<table> <thead> <tr> <th>分类名称</th> <th>操作</th> </tr> </thead> <tbody> @foreach($categories as $item) <tr> <td>{{ $item['full_path'] }}</td> <td><a href="{{ route('category.edit', $item['id']) }}">编辑</a></td> </tr> @endforeach </tbody> </table>
内容的提问来源于stack exchange,提问作者Muhammet Ali
相关产品推荐
相关产品推荐

