import{_ as i,o as a,c as t,a2 as h}from"./chunks/framework.BbmSSMjL.js";const g=JSON.parse('{"title":"8.5 字典数据接口","description":"","frontmatter":{},"headers":[],"relativePath":"zh/api-spec/dict-api.md","filePath":"zh/api-spec/dict-api.md"}'),n={name:"zh/api-spec/dict-api.md"};function k(l,s,p,e,d,r){return a(),t("div",null,[...s[0]||(s[0]=[h(`

8.5 字典数据接口 ​

概述

字典数据接口分为两组:字典管理(DictController)和字典项管理(DictItemController)。前端通过字典编码获取字典项列表用于下拉框,后台通过管理接口维护字典数据。字典项变更时 DictItemObserver 自动失效缓存。

接口总览 ​

字典管理(DictController) ​

方法URL权限码说明
GET/api/dict/pagesys:dict:page字典分页列表
GET/api/dict/detail/{id}sys:dict:detail字典详情
POST/api/dict/addsys:dict:add添加字典
PUT/api/dict/updatesys:dict:update修改字典
DELETE/api/dict/delete/{id}sys:dict:delete删除字典
DELETE/api/dict/batchDeletesys:dict:batchDelete批量删除字典
GET/api/dict/refreshCachesys:dict:update刷新字典缓存(#[DemoAllow] 演示环境放行)

字典项管理(DictItemController) ​

方法URL权限码说明
GET/api/dict/item/pagesys:dict:page字典项分页列表
GET/api/dict/item/detail/{id}sys:dict:detail字典项详情
POST/api/dict/item/addsys:dict:add添加字典项
PUT/api/dict/item/updatesys:dict:update修改字典项
DELETE/api/dict/item/delete/{id}sys:dict:delete删除字典项
DELETE/api/dict/item/batchDeletesys:dict:batchDelete批量删除字典项
GET/api/dict/item/getDictItemList/{code}—按编码获取字典项列表

批量删除为 DELETE

本项目 batchDelete 系列接口统一为 DELETE 方法(请求体传 ids 数组——DELETE 方法携带 body)。

按编码获取字典项(最常用) ​

接口信息 ​

项目说明
URLGET /api/dict/item/getDictItemList/{code}
权限无需额外权限注解(已登录即可,位于 auth.jwt 组内)
用途前端下拉框数据源

请求示例 ​

bash
GET /api/dict/item/getDictItemList/gender
Authorization: Bearer <token>

成功响应 ​

json
{
    "code": 0,
    "ok": true,
    "msg": "操作成功",
    "data": [
        { "id": 1, "name": "男", "value": "1", "sort": 1, "note": "" },
        { "id": 2, "name": "女", "value": "2", "sort": 2, "note": "" },
        { "id": 3, "name": "保密", "value": "3", "sort": 3, "note": "" }
    ]
}

响应字段 ​

字段类型说明
idnumber字典项 ID
namestring字典项名称(显示标签)
valuestring字典项值(存储值)
sortnumber排序
notestring备注

常用字典编码(以初始化脚本为准) ​

编码说明字典项
gender性别1=男, 2=女, 3=保密
user_status用户状态1=正常, 2=禁用
tenant_status租户状态1=启用, 0=禁用
example_type案例类型1=类型1, 2=类型2, 3=类型3, 4=类型4
example_status案例状态1=在用, 2=停用

(完整字典可在「数据管理 → 字典管理」中查看。)

刷新字典缓存 ​

项目说明
URLGET /api/dict/refreshCache
权限sys:dict:update
演示环境允许执行(标注 #[DemoAllow])

正常情况无需手动刷新

字典项通过后台接口增删改时,DictItemObserver 自动清除对应字典缓存。本接口用于绕过模型直接改库后的手动兜底,或运维批量刷新。

bash
GET /api/dict/refreshCache
Authorization: Bearer <token>

响应:

json
{
    "code": 0,
    "ok": true,
    "msg": "缓存刷新成功",
    "data": null
}

命令行兜底:php artisan dict:clear-cache。

前端使用 ​

获取字典项 ​

typescript
// ui/src/api/common/index.ts(实际代码)
/**
 * 根据字典编码查询字典项数据
 * @param code 字典编码
 * @returns 返回结果
 */
export function getDictItemByCode(code) {
  return http.request({
    url: '/dict/item/getDictItemList/' + code,
    method: 'GET',
  });
}

下拉框使用 ​

vue
<template>
  <n-select
    v-model:value="formData.status"
    :options="statusOptions"
    placeholder="请选择状态"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getDictItemByCode } from '@/api/common/index';

const statusOptions = ref([]);

onMounted(async () => {
  const list = await getDictItemByCode('example_status');
  // n-select 的 options 需要 { label, value } 结构
  statusOptions.value = list.map((item) => ({ label: item.name, value: item.value }));
});
</script>

多个字典批量获取 ​

typescript
const [genderOptions, statusOptions] = await Promise.all([
  getDictItemByCode('gender'),
  getDictItemByCode('user_status'),
]);

枚举显示名自动翻译 ​

Service 中配置 serializeMaps(需 use HasSerializeMaps)后,查询数据自动补全 {字段名}Text:

php
protected array $serializeMaps = [
    'status' => 'example_status',
];
json
// API 响应自动包含 statusText
{ "id": 1, "name": "测试", "status": 1, "statusText": "在用" }

缓存机制

DictCacheService 采用两级缓存(请求级 + Redis 持久缓存)。变更一致性由 Observer 保证;详见 4.8 缓存架构设计 与 5.10 字典模块。

后端 DictCacheService 调用 ​

php
use App\\Services\\DictCacheService;

// 根据值获取名称
$text = DictCacheService::getText('gender', 1);  // '男'

// 根据名称反向获取值
$value = DictCacheService::getValue('gender', '男');  // '1'

// 获取下拉框选项
$options = DictCacheService::getOptions('gender');
// [['label'=>'男','value'=>'1'], ['label'=>'女','value'=>'2'], ...]

// 批量获取多个字典映射(列表翻译一次取词)
$maps = DictCacheService::getBatchTextMaps(['gender', 'user_status']);

// 清除缓存
DictCacheService::clearCache('gender');    // 清除指定字典
DictCacheService::clearAllCache();         // 清除所有字典
`,41)])])}const y=i(n,[["render",k]]);export{g as __pageData,y as default};