首页 > 解决方案 > 更新 typeORM 实体中的所有记录

问题描述

任何人都知道有什么方法可以将所有行/记录更新为一个值。例如:布尔值?

我的用例是通过将 isRead 更改为 true 来更新所有通知的状态。提前致谢。

标签: node.jsnestjstypeorm

解决方案


有几种方法可以更新实体。

  1. EntityManagerRepository提供一种update(criteria, partialUpdate)方法。
await notificationRepository.update({}, { isRead: true });
// executes UPDATE notification SET isRead = true

这也将允许您指定一个标准应该更新哪些记录,例如

await notificationRepository.update({ userId: 123} , { isRead: true });
// executes UPDATE notification SET isRead = true WHERE userId = 123

update() 在此处查找文档。

  1. 使用迁移

如果您想将所有记录的 isRead 设置为 true,因为您添加了此字段并且所有现有通知都应标记为已读,则可以通过迁移来完成。一次迁移只会执行一次。

这就是迁移的样子:

export class SetIsReadTrue1626875696087 implements MigrationInterface {
    name = 'SetIsReadTrue1626875696087';

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query('UPDATE `notification` SET `isRead` = true');
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query('UPDATE `notification` SET `isRead` = false');
    }
}

推荐阅读