更新
save 方法
save() 方法会根据实体是否有主键值来决定执行插入还是更新操作:
ts
import { getORM } from '@ibestservices/ibest-orm';
const orm = getORM();
// 查询用户
const user = orm.query(User).where({ id: 1 }).first();
if (user) {
// 修改字段
user.name = '张三';
user.age = 25;
// 保存更新(有主键值,执行 UPDATE)
orm.save(user);
}update 方法
使用 update() 方法可以批量更新符合条件的记录:
ts
// 更新所有年龄大于 18 的用户状态
orm.query(User)
.where({ age: { gt: 18 } })
.update({ status: 'adult' });
// 更新指定 ID 的用户
orm.query(User)
.where({ id: 1 })
.update({ name: '李四', age: 30 });自动更新时间戳
如果模型使用了 @UpdatedAt 装饰器,更新时会自动填充时间:
ts
import { Table, Column, PrimaryKey, UpdatedAt } from '@ibestservices/ibest-orm';
@Table()
class Article {
@PrimaryKey()
id?: number;
@Column()
title?: string;
@UpdatedAt()
updatedAt?: string; // 更新时自动填充
}
const article = orm.query(Article).where({ id: 1 }).first();
article.title = '新标题';
orm.save(article); // updatedAt 自动更新条件更新
支持多种条件组合:
ts
// 使用多个条件
orm.query(User)
.where({ status: 'active' })
.where({ age: { gte: 18 } })
.update({ verified: true });
// 使用 IN 条件
orm.query(User)
.whereIn('id', [1, 2, 3])
.update({ role: 'admin' });注意事项
- 必须有条件:为避免误操作,建议更新时始终添加 WHERE 条件
- 返回值:
update()返回受影响的行数 - 事务支持:批量更新建议在事务中执行
ts
orm.transaction(() => {
orm.query(User).where({ status: 'pending' }).update({ status: 'active' });
orm.query(Order).where({ userId: 1 }).update({ processed: true });
});