常见业务场景
本文收录开发中高频遇到的业务场景和实现思路。
文件上传与图片处理
后端上传接口
系统内置了文件上传接口,无需额外开发:
POST /adminapi/upload/image — 图片上传
POST /adminapi/upload/file — 文件上传上传后返回:
json
{
"code": 200,
"message": "上传成功",
"data": {
"url": "https://your-domain.com/storage/uploads/2026/04/xxx.jpg",
"path": "/storage/uploads/2026/04/xxx.jpg"
}
}url:完整 URL,前端显示用path:相对路径,数据库存储用
前端上传组件
使用 el-upload 组件:
vue
<el-upload
action="/adminapi/upload/image"
:headers="{ Authorization: `Bearer ${token}` }"
:on-success="handleUploadSuccess"
>
<el-button type="primary">上传图片</el-button>
</el-upload>图片 URL 拼接
从数据库读取的是相对路径,显示时需要拼接域名:
typescript
import { useAppStore } from '@/store/modules/app.store'
const appStore = useAppStore()
// 拼接完整 URL
const fullUrl = appStore.getImageUrl(item.cover_image)数据导入/导出
Excel 导入
系统内置了 ImportData 组件,使用步骤:
- 准备 Excel 模板(xlsx 格式)
- 后端 Service 实现导入逻辑
- 前端引入
ImportData组件
vue
<ImportData
:action="'/adminapi/xxx/import'"
:template-url="'/adminapi/xxx/import-template'"
@success="getList"
/>Excel 导出
后端使用 PhpSpreadsheet 生成 Excel:
php
// Controller 中
public function export(): \think\Response
{
$params = $this->request->get();
$filePath = $this->xxxService->export($params);
return download($filePath, '导出数据.xlsx');
}树形数据
适用于分类、部门、地区等层级数据。
后端
Repository 中添加树形查询方法:
php
public function getTree(): array
{
$list = $this->model
->where('deleted_at', null)
->order('sort', 'asc')
->select()
->toArray();
return $this->buildTree($list);
}
private function buildTree(array $list, int $pid = 0): array
{
$tree = [];
foreach ($list as $item) {
if ($item['pid'] == $pid) {
$item['children'] = $this->buildTree($list, $item['id']);
$tree[] = $item;
}
}
return $tree;
}前端
使用 el-table 树形模式:
vue
<el-table :data="treeData" row-key="id" :tree-props="{ children: 'children' }">
<el-table-column prop="title" label="名称" />
<!-- ... -->
</el-table>支付集成
后端配置
在管理后台「系统配置 → 开放平台」中配置微信/支付宝的商户号、密钥等信息。
支付流程:
- 前端调用充值接口,传入金额和客户端类型
- 后端根据客户端类型自动选择支付方式(JSAPI/H5/Native)
- 返回支付参数,前端调起支付
- 支付完成后,后端异步回调更新订单状态
详细集成文档参考 移动端支付集成。
消息通知
站内信
php
// Service 中发送通知
$this->trigger('user.notification.created', [
'user_id' => $userId,
'title' => '通知标题',
'content' => '通知内容',
'type' => 'system',
]);消息通知已改为异步队列发送,确保 .env 中 QUEUE.CONNECTOR = redis 且队列进程已启动。
短信
通过消息通道配置,在管理后台「系统配置 → 消息通道」中配置短信服务商(阿里云、腾讯云等)。
定时任务
添加命令
php
// app/command/MyTask.php
<?php
declare(strict_types=1);
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class MyTask extends Command
{
protected function configure(): void
{
$this->setName('my:task')->setDescription('我的定时任务');
}
protected function execute(Input $input, Output $output): void
{
// 任务逻辑
$output->writeln('任务执行完成');
}
}注册命令
在 server/config/console.php 的 commands 数组中注册:
php
'commands' => [
\app\command\MyTask::class,
],配置 Cron
在服务器(或宝塔面板)中添加定时任务:
bash
# 每天凌晨 2 点执行
0 2 * * * cd /path/to/server && php think my:task系统内置的定时命令:
| 命令 | 说明 | 建议频率 |
|---|---|---|
php think log:archive | 清理过期管理员日志 | 每天一次 |