更新数据 save,update,updatewhere
数据模型内置了多种更新处理器,可用于服务接口(API
)和数据流(Flow
)中实现数据更新功能。主要包括以下几种更新方式:
save
: 保存单条记录,如果记录存在则更新,不存在则创建update
: 更新单条记录,根据主键ID更新updatewhere
: 批量更新记录,根据条件更新多条记录
这些处理器支持关联数据的更新,并会自动处理时间戳、软删除等特性。
示例:
新建模型
新增models/category.mod.json
文件,写入以下内容:
json
{
"name": "书籍分类",
"table": {
"name": "category",
"comment": "书籍分类"
},
"columns": [
{
"label": "ID",
"name": "id",
"type": "ID",
"comment": "ID",
"primary": true
},
{
"label": "父级id",
"name": "parent_id",
"type": "integer",
"nullable": true
},
{
"label": "分类名称",
"name": "name",
"type": "string",
"length": 128,
"index": true
}
],
"relations": {
"book": {
"type": "hasMany",
"model": "book",
"key": "category_id",
"foreign": "id",
"query": {}
},
"parent": {
"type": "hasOne",
"model": "category",
"key": "id",
"foreign": "parent_id",
"query": {}
}
},
"option": {
"timestamps": true,
"soft_deletes": true
},
"values": [
{
"id": 1,
"parent_id": null,
"name": "文史类"
},
{
"id": 2,
"parent_id": 1,
"name": "历史"
},
{
"id": 3,
"parent_id": 1,
"name": "古诗"
},
{
"id": 4,
"parent_id": null,
"name": "理工类"
},
{
"id": 5,
"parent_id": 4,
"name": "数学"
},
{
"id": 6,
"parent_id": 4,
"name": "物理"
}
]
}
Save 传入 id 则为保存scripts/test.js
javascript
function Save() {
return Process('models.category.save', {
id: 6,
parent_id: 1,
name: '语文'
});
}
Update 更新,第一个参数为 id,第二个参数为更新对象:
javascript
function Update() {
return Process('models.category.update', 9, {
parent_id: 1,
name: '英语'
});
}
UpdateWhere 批量更新
javascript
function UpdateWhere() {
return Process(
'models.category.updatewhere',
{
wheres: [{ column: 'parent_id', value: 1 }]
},
{
name: '数学'
}
);
}
执行以下命令测试更新功能:
bash
# 测试保存功能
yao run scripts.test.Save
# 测试批量更新
yao run scripts.test.UpdateWhere
# 测试单条更新
yao run scripts.test.Update
高级用法
1. 关联数据更新
可以在更新时同时更新关联数据:
javascript
function SaveWithRelation() {
return Process('models.category.save', {
id: 6,
name: '编程语言',
// 同时更新关联的图书数据
book: [
{ name: 'Python入门', status: 1 },
{ name: 'JavaScript高级编程', status: 1 }
]
});
}
2. 条件更新示例
使用复杂条件进行批量更新:
javascript
function UpdateWithCondition() {
return Process(
'models.category.updatewhere',
{
wheres: [
{ column: 'parent_id', value: 4 },
{ method: 'orWhere', column: 'name', value: '%语言%', op: 'like' }
]
},
{
status: 0,
updated_at: new Date().toISOString()
}
);
}
3. 更新钩子
可以通过定义钩子函数来在更新前后执行自定义逻辑:
javascript
// hooks/category.js
function BeforeUpdate(payload) {
// 更新前的处理
payload.data.updated_by = Process('session.get', 'user_id');
return payload;
}
function AfterUpdate(payload) {
// 更新后的处理
Process('models.log.create', {
action: 'update',
model: 'category',
data: payload
});
return payload;
}