【问题标题】:Update all records in a typeORM entity更新 typeORM 实体中的所有记录
【发布时间】:2021-07-22 15:06:39
【问题描述】:

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

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

【问题讨论】:

    标签: node.js nestjs typeorm


    【解决方案1】:

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

    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');
        }
    }
    

    【讨论】:

    • 哇,这是一个相当全面的答案。让我试试看。非常感谢您的帮助!
    • @hweiu321 希望它对你有用吗?如果它回答了您的问题,请不要忘记接受答案。
    猜你喜欢
    • 2018-09-10
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2021-06-05
    • 2021-09-21
    相关资源
    最近更新 更多