You need to enable JavaScript to run this app. Golang GORM操作Postgres执行UPSERT时clause.OnConflict不生成WHERE条件
优惠活动
大模型
产品
解决方案
定价
更多

Golang GORM操作Postgres执行UPSERT时clause.OnConflict不生成WHERE条件

你原来的代码无法生成WHERE子句的原因是字段用错了:clause.OnConflict结构体中的Where字段用于定义冲突目标的过滤条件(通常搭配部分唯一索引场景使用),如果要给DO UPDATE执行阶段加过滤逻辑,需要使用UpdateWhere字段。如果运行时提示UpdateWhere字段不存在,升级GORM到v1.23.0及以上版本即可。

修正后的代码如下:

result := tx.Table("attributes").Clauses(clause.OnConflict{
    Columns:   []clause.Column{{Table: "attributes", Name: "id"}},
    UpdateAll: true,
    // DO UPDATE 阶段的过滤条件需定义在 UpdateWhere 中
    UpdateWhere: clause.Where{
        Exprs: []clause.Expression{clause.Eq{Column: "attributes.organization_id", Value: 2}},
    },
}).Create(&attributes)

上述代码会自动生成你期望的带WHERE子句的Upsert SQL,冲突更新时只会修改organization_id等于2的行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 00:36:04