关联表中数值递增操作不符合预期问题求助
关联表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
问题原因
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
相关产品推荐
相关产品推荐


