feat(api): 新增分类查询接口(列表+详情,支持树形结构)

This commit is contained in:
augushong
2026-04-28 21:01:27 +08:00
parent 004f4454f4
commit bb08dee91d
2 changed files with 93 additions and 2 deletions

View File

@@ -0,0 +1,91 @@
<?php
namespace app\api\controller;
use app\BaseController;
use app\model\Category;
use app\middleware\ApiKeyAuth;
class Categories extends BaseController
{
protected $middleware = [ApiKeyAuth::class];
/**
* 分类列表
*/
public function index()
{
$page = $this->request->param('page', 1, 'intval');
$limit = $this->request->param('limit', 15, 'intval');
$type = $this->request->param('type', '');
$pid = $this->request->param('pid', '', 'intval');
$tree = $this->request->param('tree', 0, 'intval');
$status_param = $this->request->param('status');
$status = is_null($status_param) ? 1 : $status_param;
if ($limit < 1) {
$limit = 1;
}
if ($limit > 100) {
$limit = 100;
}
$query = Category::where('delete_time', 0);
if ($status !== '') {
$query->where('status', $status);
}
if (!empty($type)) {
$query->where('type', $type);
}
if ($pid !== '') {
$query->where('pid', $pid);
}
$query->order('sort asc');
if ($tree) {
$list = $query->select()->toArray();
$treeList = array2level($list, 0, 0);
return json_message(['list' => $treeList]);
}
$list = $query->paginate([
'page' => $page,
'list_rows' => $limit,
]);
return json_message([
'list' => $list->items(),
'total' => $list->total(),
'page' => $page,
]);
}
/**
* 分类详情
*/
public function read()
{
$id = $this->request->param('id', 0, 'intval');
if ($id <= 0) {
return json_message('参数错误');
}
$category = Category::where('delete_time', 0)
->where('id', $id)
->find();
if (empty($category)) {
return json_message('分类不存在');
}
$category->append(['model_parent', 'model_siblings']);
return json_message($category);
}
}