Agent 可以拥有自己的私有数据库表。在 Agent 的 `models/` 目录下定义 `.mod.yao` 文件,Yao 会在启动时自动迁移数据表。
## 目录结构
```
assistants/myns/myagent/
├── package.yao
├── models/
│ ├── record.mod.yao
│ └── label.mod.yao
```
### Model ID 与表名
框架从文件路径中推导出 **Model ID**:
```
assistants/<namespace>/<agent>/models/<name>.mod.yao
↓
agents.<namespace>.<agent>.<name>
```
`assistants/myns/myagent/models/record.mod.yao` → Model ID 为 `agents.myns.myagent.record`。
**实际数据库表名**会自动加前缀:
```
前缀 = "agents_<namespace>_<agent>_"
表名 = 前缀 + table.name(来自 .mod.yao)
```
因此 `"table": {"name": "record"}` → 实际数据库表为 `agents_myns_myagent_record`。
你无需直接引用前缀——始终使用 Model ID 即可。
## 定义 Model
```json
{
"name": "Record",
"table": { "name": "record" },
"columns": [
{ "name": "id", "type": "ID", "primary": true },
{ "name": "team_id", "type": "string", "length": 100, "nullable": false, "index": true },
{ "name": "title", "type": "string", "length": 500, "nullable": false },
{ "name": "content", "type": "text", "nullable": true },
{
"name": "status",
"type": "enum",
"option": ["active", "archived"],
"default": "active",
"nullable": false,
"index": true
}
],
"indexes": [
{ "name": "idx_team_status", "columns": ["team_id", "status"], "type": "index" }
],
"option": {
"timestamps": true,
"soft_deletes": true
}
}
```
### 列类型
| 类型 | 说明 |
|------|------|
| `ID` | 自增主键 |
| `string` | VARCHAR — 用 `length` 设置长度 |
| `text` / `mediumText` / `longText` | TEXT 类型变体 |
| `integer` / `bigInteger` | 整数类型 |
| `decimal` / `float` | 数值类型 |
| `boolean` | 布尔值 |
| `enum` | 枚举 — 需要 `option: [...]` |
| `json` | JSON 列 |
| `date` / `datetime` / `timestamp` | 日期/时间类型 |
### 常用选项
```json
"option": {
"timestamps": true, // 添加 created_at、updated_at 列
"soft_deletes": true // 添加 deleted_at;Delete() 执行软删除而非真实删除
}
```
## 在 Hook 中查询
Process 名称格式为 `models.<model-id>.<Method>`:
```typescript
import { Process } from "@yao/runtime";
const MODEL = "agents.myns.myagent";
export function Create(ctx, messages) {
// 获取记录列表
const records = Process(`models.${MODEL}.record.Get`, {
wheres: [
{ column: "team_id", value: ctx.authorized.team_id },
{ column: "status", value: "active" }
],
orders: [{ column: "created_at", option: "desc" }],
limit: 20
});
// 保存一条记录
const id = Process(`models.${MODEL}.record.Create`, {
team_id: ctx.authorized.team_id,
title: "...",
content: "...",
status: "active"
});
return { messages };
}
```
### 内置 Model Process
| Process | 说明 |
|---------|------|
| `models.<id>.Find(id, params)` | 按主键查询单条记录 |
| `models.<id>.Get(params)` | 查询记录列表 |
| `models.<id>.Paginate(params, page, pageSize)` | 分页查询 |
| `models.<id>.Create(row)` | 插入一条记录,返回 ID |
| `models.<id>.Save(row)` | Upsert(创建或更新) |
| `models.<id>.Update(id, row)` | 按主键更新 |
| `models.<id>.Delete(id)` | 删除(启用软删除时为软删除) |
| `models.<id>.Destroy(id)` | 硬删除 |
## 下一步
编写操作这些 Model 的业务逻辑:
- **[脚本与 Process →](./scripts)** — 将 TypeScript 函数导出为 Yao Process