【发布时间】:2018-12-15 09:04:12
【问题描述】:
如何通过 TypeORM 中的原始查询进行批量更新?
例如,我们有具有属性 name
的模型 User
如何在一次事务中更改少数用户的名称?
typeorm 版本:0.2.7
数据库:postgress
【问题讨论】:
标签: node.js typeorm bulkupdate
如何通过 TypeORM 中的原始查询进行批量更新?
例如,我们有具有属性 name
的模型 User
如何在一次事务中更改少数用户的名称?
typeorm 版本:0.2.7
数据库:postgress
【问题讨论】:
标签: node.js typeorm bulkupdate
要批量更新,你可以用set方法更新,当你可以使用orm函数时,总是建议不要使用原始查询。
import {getConnection, In} from "typeorm";
const userIds = [1,2,3];
await getConnection()
.createQueryBuilder()
.update(User)
.set({ isaSeniorCitizen: true })
.where({ id: In(userIds) })
.execute();
【讨论】:
.where({ id: In(userIds) })。因为你的问题是关于how to bulk update
您也可以通过这种方式使用存储库 api 更新多行:
await repository.update(
{
id: In([1,2,3,4,5]),
},
{ selected: true },
);
【讨论】:
您可以使用QueryBuilder:
import {getConnection} from "typeorm";
await getConnection()
.createQueryBuilder()
.update(User)
.set({ firstName: "Timber", lastName: "Saw" })
.where("id = :id", { id: 1 })
.execute();
或query()方法:
getRepository(User).query('UPDATE `users` SET firstName = 'Timber', lastName = 'Saw' WHERE id = 1')
显然,对于批量更新,您可以使用 QueryBuilder 执行 .where({ id: In(userIds) }) 或使用原始查询执行 WHERE id IN (${userIds.join(',')})。
【讨论】:
不支持更新具有不同值的多个列。 Typeorm repo 中有一个未解决的问题:https://github.com/typeorm/typeorm/issues/7326
@Roman-Pekar 对Update multiple rows in same query using PostgreSQL 的回答中显示了如何使用原始 psql 执行此操作。
另一个“解决方案”是在 postgres 数据库中创建一个存储函数并调用它。在另一个类似问题的 cmets 中,我展示了一个如何做到这一点的示例:typeorm efficient bulk update
【讨论】:
你可以这样做
import {getConnection } from "typeorm";
const userIds = [1,2,3];
await getConnection()
.createQueryBuilder()
.update(User)
.set({ isaSeniorCitizen: true })
.whereInIds(userIds)
.execute();
【讨论】: