更新 typeORM 实体中的所有记录

Update all records in a typeORM entity

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

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

更新实体有多种方法。

  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() here.

的文档
  1. 使用migrations

如果因为添加了此字段而要将所有记录的 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');
    }
}