【问题标题】:Bulk update via raw query in TypeORM通过 TypeORM 中的原始查询进行批量更新
【发布时间】:2018-12-15 09:04:12
【问题描述】:

如何通过 TypeORM 中的原始查询进行批量更新?
例如,我们有具有属性 name
的模型 User 如何在一次事务中更改少数用户的名称?

typeorm 版本:0.2.7
数据库:postgress

【问题讨论】:

    标签: node.js typeorm bulkupdate


    【解决方案1】:

    要批量更新,你可以用set方法更新,当你可以使用orm函数时,总是建议不要使用原始查询。

    
    import {getConnection, In} from "typeorm";
    const userIds = [1,2,3];
    
    await getConnection()
      .createQueryBuilder()
      .update(User)
      .set({ isaSeniorCitizen: true })
      .where({ id: In(userIds) })
      .execute();
    
    

    【讨论】:

    • 这个和第一个答案有什么区别?
    • 它可以让您针对多条记录进行更新:.where({ id: In(userIds) })。因为你的问题是关于how to bulk update
    • 但在这种情况下,订阅者无法正常工作,有什么解决方案吗? @aitchkhan
    【解决方案2】:

    您也可以通过这种方式使用存储库 api 更新多行:

    await repository.update(
      {
        id: In([1,2,3,4,5]),
      },
      { selected: true },
    );
    

    【讨论】:

      【解决方案3】:

      您可以使用QueryBuilder:

      import {getConnection} from "typeorm";
      
      await getConnection()
        .createQueryBuilder()
        .update(User)
        .set({ firstName: "Timber", lastName: "Saw" })
        .where("id = :id", { id: 1 })
        .execute();
      

      query()方法:

      getRepository(User).query('UPDATE `users` SET firstName = 'Timber', lastName = 'Saw' WHERE id = 1')
      

      显然,对于批量更新,您可以使用 QueryBuilder 执行 .where({ id: In(userIds) }) 或使用原始查询执行 WHERE id IN (${userIds.join(',')})

      【讨论】:

      • 我不确定这个查询是谁批量更新的?
      • 对不起,我的问题是“如何”这个查询批量更新它?
      【解决方案4】:

      不支持更新具有不同值的多个列。 Typeorm repo 中有一个未解决的问题:https://github.com/typeorm/typeorm/issues/7326

      @Roman-Pekar 对Update multiple rows in same query using PostgreSQL 的回答中显示了如何使用原始 psql 执行此操作。

      另一个“解决方案”是在 postgres 数据库中创建一个存储函数并调用它。在另一个类似问题的 cmets 中,我展示了一个如何做到这一点的示例:typeorm efficient bulk update

      【讨论】:

        【解决方案5】:

        你可以这样做

        import {getConnection } from "typeorm";
        const userIds = [1,2,3];
        
        await getConnection()
          .createQueryBuilder()
          .update(User)
          .set({ isaSeniorCitizen: true })
          .whereInIds(userIds)
          .execute();
        

        【讨论】:

          猜你喜欢
          • 2014-10-21
          • 2015-02-07
          • 1970-01-01
          • 2021-01-24
          • 2013-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多