Laravel Filament嵌套分类列表展示的问题与优化尝试
Laravel + Filament + Adjacency List 树形分类展示问题及尝试方案
我正在使用Laravel、Filament Admin面板和staudenmeir/laravel-adjacency-list扩展,尝试通过getEloquentQuery()在CategoryResource列表页正确展示嵌套树形结构。分类表categories包含id、parent_id、name字段,自身存在hasMany关联。
通过以下代码可实现子分类直接显示在父分类下方的嵌套结构:
public static function getEloquentQuery(): Builder { return parent::getEloquentQuery()->tree()->depthFirst(); }
但存在两个问题:
- 与alperenersoy/filament-export插件兼容问题:CTE查询导致导出功能报错,还原为简单的
getEloquentQuery()则插件正常工作; - 层级排序问题:希望嵌套层级内的分类按名称字母序排列,例如父分类“Blue Plan”下的子分类“AAA Plan”应排在“CCC Plan”之前。
我尝试了两种修改方案:
方案一:修改laravel-adjacency-list的输出
public static function getEloquentQuery(): Builder { $sql = parent::getEloquentQuery()->getExpressionGrammar()->compileOrderByPath(); $sql = substr($sql, 0, -5); return parent::getEloquentQuery()->tree()->orderByRaw($sql . '), name ASC'); }
方案二:使用递归查询约束
public static function getEloquentQuery(): Builder { $tree = Category::withRecursiveQueryConstraint(function (Builder $query) { $query->where('categories.name', '=', 'ADVENT'); $query->orderBy('name'); }, function () { return parent::getEloquentQuery()->tree()->depthFirst(); }); return $tree; }
内容的提问来源于stack exchange,提问作者Curtis B
相关产品推荐
相关产品推荐

