This commit is contained in:
liu
2026-09-04 22:10:28 +08:00
parent cf1d3a6229
commit 1e25459676
4 changed files with 65 additions and 1 deletions
+30
View File
@@ -74,6 +74,36 @@ class ProductCategoryModel extends Model
return static::buildTree($query->get($columns)->toArray());
}
/**
* 按树展示顺序(sort/id 深度优先)获取分类 ID 列表,供商品列表等按分类顺序排序
*
* @param bool $onlyEnabled 是否仅包含启用分类
* @return array<int, int>
*/
public static function getTreeOrderedIds(bool $onlyEnabled = false): array
{
return static::flattenTreeIds(static::getTreeData(['id', 'parent_id'], $onlyEnabled));
}
/**
* 深度优先展开分类树为有序 ID 列表
*
* @param array<int, array<string, mixed>> $tree
* @return array<int, int>
*/
private static function flattenTreeIds(array $tree): array
{
$ids = [];
foreach ($tree as $node) {
$ids[] = (int) $node['id'];
if (!empty($node['children'])) {
$ids = [...$ids, ...static::flattenTreeIds($node['children'])];
}
}
return $ids;
}
/**
* 将扁平分类列表组装为树
*