You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM 1.0迁移:onConflict转orUpdate的自定义SQL实现问题

解决TypeORM 1.0中替换onConflict实现自定义冲突更新逻辑的问题

场景1:冲突时自增固定数值

原逻辑为插入新行时requested设为3或1,行已存在则requested自增1,改写方式如下:

await this.missingImgRepository.createQueryBuilder()
  .insert()
  .into(MissingImgEntity)
  .values({
    domain: domain,
    requested: isTopLevel ? 3 : 1,
  })
  // 用orUpdate替代onConflict,通过对象定义更新逻辑
  .orUpdate(
    {
      requested: () => `"missing_img"."requested" + 1`
    },
    ["domain"] // 指定触发冲突的唯一键字段
  )
  .execute();

场景2:冲突时自增指定值并更新其他字段

针对需要自增自定义requestPoints、同时更新account_id的场景,结合参数绑定规避SQL注入:

await this.missingImgRepository.createQueryBuilder()
  .insert()
  .into(MissingImgEntity)
  .values({
    domain: domain,
    requested: initialRequestedValue, // 填入插入时的requested初始值
    account_id: userId
  })
  .orUpdate(
    {
      requested: () => `"missing_img"."requested" + :requestPoints`,
      account_id: () => `:userId`
    },
    ["domain"],
    {
      parameters: { requestPoints, userId } // 绑定参数,避免注入风险
    }
  )
  .execute();

关键说明

TypeORM 1.0的orUpdate并非仅支持传入字段数组,还可以通过对象类型的更新规则实现自定义逻辑:当值为箭头函数时,函数返回的字符串会直接作为SQL表达式生效,完全可以替代原onConflict中的自定义DO UPDATE语句。

内容的提问来源于stack exchange,提问作者Juraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 01:27:32