排序
This commit is contained in:
@@ -47,6 +47,18 @@ class ProductController extends BaseMiniController
|
||||
});
|
||||
}
|
||||
|
||||
// 先按分类树展示顺序(与小程序分类栏一致;不在启用分类树中的商品排最后),再按商品排序
|
||||
$categoryIds = ProductCategoryModel::getTreeOrderedIds(true);
|
||||
if ($categoryIds !== []) {
|
||||
$cases = [];
|
||||
foreach ($categoryIds as $position => $categoryId) {
|
||||
$cases[] = "WHEN {$categoryId} THEN {$position}";
|
||||
}
|
||||
$query->orderByRaw(
|
||||
'CASE category_id ' . implode(' ', $cases) . ' ELSE ' . count($categoryIds) . ' END'
|
||||
);
|
||||
}
|
||||
|
||||
$pageSize = (int) $request->input('pageSize', 10);
|
||||
$paginator = $query->orderBy('sort', 'desc')
|
||||
->orderBy('id')
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将扁平分类列表组装为树
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user