首页 > 解决方案 > 子句.OnConflict() 在 UPSERT 期间不生成 where 条件

问题描述

我正在将 golang 与 gorm 一起使用并在 Postgres 上运行,并且需要执行 Upsert。任何帮助表示赞赏。

我正在插入“属性”表,并且在“id”冲突时,只有当“organization_id”与给定值匹配时,才应更新该行。

基于来自 https://gorm.io/docs/create.html#Upsert-On-Conflicthttps://github.com/go-gorm/gorm/blob/master/clause/where_test.go的样本

result := tx.Table("attributes").Clauses(clause.OnConflict{
    Columns: []clause.Column{{Table: "attributes", Name: "id"}},
    Where:     clause.Where{Exprs: []clause.Expression{clause.Eq{Column: "organization_id", Value: "2"}}},
    UpdateAll: true,
}).Create(&attributes)

上面的代码生成以下没有 WHERE 子句的 SQL :

INSERT INTO "attributes" ("organization_id","name","id") 
VALUES (2,"demo",15)
ON CONFLICT ("id") DO UPDATE SET "organization_id"="excluded"."organization_id", "name"="excluded"."name",
RETURNING "id"

带有 WHERE 子句的预期 SQL:

INSERT INTO "attributes" ("organization_id","name","id") 
VALUES (2,"demo",15)
ON CONFLICT ("id") DO UPDATE SET "organization_id"="excluded"."organization_id", "name"="excluded"."name",
WHERE attributes.organization_id=2 
RETURNING "id"

标签: postgresqlgogo-gorm

解决方案


推荐阅读