【问题标题】:TypeORM: update on conflict without idTypeORM:更新没有 id 的冲突
【发布时间】:2021-05-30 04:28:00
【问题描述】:

我想批量处理insertupdate if exists 行在事先不知道行的id(如果存在)的情况下。我正在使用TypeORM。在这种情况下,我想update 存在uniqueKey 的行与一个新的titleinsert 不存在。

const data = [
  {title: 'New Title', user: 123, uniqueKey: 'abc'},
  {title: 'Another New Title', user: 123, uniqueKey: 'xyz' }
 ]

await repo
    .createQueryBuilder()
    .insert()
    .into(Posts)
    .values(data)
    .orUpdate({ conflict_target: ['uniqueKey'], overwrite: ['title']  })
    .execute();

上面抛出错误:

Error: Cannot update entity because entity id is not set in the entity.

如果有更好的方法来批量处理upsert,欢迎提出建议。

【问题讨论】:

    标签: mysql sql node.js typeorm


    【解决方案1】:

    我在尝试批量 .orUpdate 一个没有“id”字段的对象数组时遇到了这个确切的问题。我所要做的就是向我导入的每个对象添加 id 字段,因为我相信它用于在执行 .orUpdate 时迭代每个对象的“元数据”。

    我也使用 MySQL,这里是我的代码(url 是 uniqueKey):

     const result = await connection
        .createQueryBuilder()
        .insert()
        .into(Channel)
        .values(data)
        .orUpdate({
          conflict_target: ["url"],
          overwrite: ["name", "imgurl", "subscribers"],
        }) //If channel exists we update its info.
        .execute()
        .catch((err) => err);
    

    当我的对象具有这种结构时,我会遇到您提到的相同错误:

    data = [{name : "name", imgurl : "imgurl", url: "url1"}, { name : "name", imgurl : "imgurl", url: "url2"}]
    

    遍历对象数组并为每个对象添加增量 id 解决了这个问题:

    data = [{id: 1, name : "name", imgurl : "imgurl", url: "url1"}, {id: 2, name : "name", imgurl : "imgurl", url: "url2"}]
    

    希望这至少可以为您提供临时解决方案。

    【讨论】:

      【解决方案2】:

      就我而言,最好的方法始终是不隐藏 SQL 数据库。

      使用透明函数构建查询甚至可能会阻止您使用纯 SQL 执行我在这里所做的事情(我不知道 node.js,但其他 SQL 包装器用这个让我窒息......)

      哦,user 是保留字;它包含当前连接到 MySQL 的用户的名称..

      INSERT INTO posts (title,userid,unique_key)
      VALUES ('New Title'        , 123, 'abc')
      ON DUPLICATE KEY UPDATE title='New Title';
      
      INSERT INTO posts (title,userid,unique_key)
      VALUES ('Another New Title', 123, 'xyz')
      ON DUPLICATE KEY UPDATE title='Another New Title';
      

      或者,对于批量插入,填充一个与posts 相同结构的临时表,然后:

      INSERT INTO posts (title,userid,unique_key)
      SELECT
        title
      , userid
      , unique_key
      FROM posts_tmp t
      ON DUPLICATE KEY UPDATE title = t.title, userid=t.userid;
      

      【讨论】:

        猜你喜欢
        • 2019-01-11
        • 2017-03-22
        • 1970-01-01
        • 2022-09-27
        • 2022-01-01
        • 2012-01-01
        • 2011-04-01
        • 2023-03-27
        • 1970-01-01
        相关资源
        最近更新 更多