簡體   English   中英

更新 typeORM 實體中的所有記錄

[英]Update all records in a typeORM entity

任何人都知道有什么方法可以將所有行/記錄更新為一個值。 例如:布爾值?

我的用例是通過將 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()文檔。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM