node.js - 更新 typeORM 实体中的所有记录
问题描述
任何人都知道有什么方法可以将所有行/记录更新为一个值。例如:布尔值?
我的用例是通过将 isRead 更改为 true 来更新所有通知的状态。提前致谢。
解决方案
有几种方法可以更新实体。
EntityManager
并Repository
提供一种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()
在此处查找文档。
- 使用迁移
如果您想将所有记录的 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');
}
}
推荐阅读
- powershell - 使用 New-WebServiceProxy 命名空间和对象问题的 Powershell 肥皂
- google-sheets - 谷歌表格功能限制
- azure - 创建的 VNet 未显示在 Azure 的路由表配置中
- python - 如何检测图像的条纹噪声?
- javascript - 如何用两个单独的javascript代码制作两个画布?
- android - sendPasswordResetEmail 现在返回“您的密码已过期或链接已被使用”
- c# - Durable Azure Function Orchestrator 是否会释放计时器锁定?
- ios - 是否可以在不使用 Swift UI 的情况下在 Xcode 11.2 或更高版本中使用 Swift 创建 App Clip?
- asp.net - HTTP 错误 403.14 - Web 服务器配置为不列出此目录的内容。在 .NET 核心 3.1 中
- python - 将带有嵌套列表的字典转换为特定的 pandas df 结构