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

关联表中数值递增操作不符合预期问题求助

关联表Upsert时数值累加异常问题

表结构定义

User表

type User @table{
  id: String! @default(expr: "auth.uid")
  createdAt: Timestamp! @default(expr: "request.time")
}

Potion表

type Potion @table{
  # ID自动生成
  name: String!
}

关联表UserPotion

用于建立User与Potion的关联:

type UserPotion @table(key: ["user", "potion"]){
  # ID自动生成
  user: User! # 自动生成外键userId
  potion: Potion! # 自动生成外键potionId
  quantity: Int! @default(value: 1)
}

执行的Mutation

mutation AddUserPotion($potionId: UUID!, $quantity: Int!) @auth(level: USER) {
  userPotion_upsert(
    data: {
      userId_expr: "auth.uid"
      potionId: $potionId
      quantity_update: {inc: $quantity}
    }
  )
}

异常现象

  • 用户已有对应药水记录时,累加操作正常;
  • 用户无对应记录时,最终数值比预期多1。例如传入$quantity=20,结果quantity变为21。

根据官方文档说明,null应被视为0,且该逻辑在普通表中正常生效,仅在关联表中出现异常:

文档说明:null treated as 0
null treated as 0


问题原因

UserPotion表的quantity字段设置了默认值1,执行upsert插入新记录时,会先将quantity赋值为默认值1,再执行inc: $quantity的累加操作,最终得到1 + $quantity的结果。文档中“null视为0”的规则仅适用于更新现有记录时字段为null的场景,不适用于插入阶段的默认值逻辑。

解决方法

方法1:区分Upsert的插入与更新分支

修改Mutation,分别定义插入和更新时的字段处理逻辑,插入时直接设置quantity为传入值,更新时执行累加:

mutation AddUserPotion($potionId: UUID!, $quantity: Int!) @auth(level: USER) {
  userPotion_upsert(
    where: {
      user_potion: {
        userId_expr: "auth.uid"
        potionId: $potionId
      }
    }
    create: {
      userId_expr: "auth.uid"
      potionId: $potionId
      quantity: $quantity
    }
    update: {
      quantity_update: {inc: $quantity}
    }
  )
}

方法2:移除字段默认值

如果不需要默认值,直接去掉quantity的@default注解,这样插入新记录时quantity会被视为0,再执行累加操作,结果与预期一致:

type UserPotion @table(key: ["user", "potion"]){
  # ID自动生成
  user: User! # 自动生成外键userId
  potion: Potion! # 自动生成外键potionId
  quantity: Int!
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:57:41