Commit 4dcf6525 authored by 刘小敏's avatar 刘小敏

新增商品分类树接口

parent 70683417
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
namespace addons\shopro\controller; namespace addons\shopro\controller;
use app\admin\model\shopro\Category as CategoryModel; use app\admin\model\shopro\Category as CategoryModel;
use think\Cache;
class Category extends Common class Category extends Common
{ {
...@@ -28,4 +29,76 @@ class Category extends Common ...@@ -28,4 +29,76 @@ class Category extends Common
$this->success('商城分类', $categories); $this->success('商城分类', $categories);
} }
// 缓存键名
const CACHE_KEY = 'shopro_category_tree';
// 缓存有效期(24小时)
const CACHE_TTL = 86400;
/**
* 获取完整分类树(包含二级、三级、四级分类)
*
* @ApiMethod (GET)
* @ApiParams (name="refresh", type="int", required=false, description="是否强制刷新缓存,1=刷新")
*/
public function tree()
{
$refresh = $this->request->param('refresh', 0);
// 如果不需要刷新缓存,先尝试从缓存获取
if (!$refresh) {
$cacheData = Cache::get(self::CACHE_KEY);
if ($cacheData) {
$this->success('分类列表', $cacheData);
}
}
// 从数据库获取一级分类
$categories = CategoryModel::where('parent_id', 0)
->normal()
->order('weigh', 'desc')
->order('id', 'desc')
->select();
// 递归获取子分类(最多四级)
foreach ($categories as &$category) {
$category['children'] = $this->getChildren($category['id'], 1);
}
unset($category);
// 将结果存入缓存
Cache::set(self::CACHE_KEY, $categories, self::CACHE_TTL);
$this->success('分类列表', $categories);
}
/**
* 递归获取子分类
*
* @param int $parentId 父分类ID
* @param int $level 当前层级(1=二级,2=三级,3=四级)
* @return array
*/
private function getChildren($parentId, $level)
{
// 最多获取到四级分类
if ($level >= 4) {
return [];
}
$children = CategoryModel::where('parent_id', $parentId)
->normal()
->order('weigh', 'desc')
->order('id', 'desc')
->select();
foreach ($children as &$child) {
$child['children'] = $this->getChildren($child['id'], $level + 1);
}
unset($child);
return $children;
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment