如何处理在一个有多个关联的数据库中插入冲突



我有以下两个模型:

type OHLCV struct {
gorm.Model
Interval         string        `gorm:"uniqueIndex:idx_ohlcv"`
Pair             string        `gorm:"uniqueIndex:idx_ohlcv"`
OpenTime         time.Time     `gorm:"uniqueIndex:idx_ohlcv"`
CloseTime        time.Time     `gorm:"uniqueIndex:idx_ohlcv"`
Open             float64       `json:"open"`
High             float64       `json:"high"`
Low              float64       `json:"low"`
Close            float64       `json:"close"`
Volume           float64       `json:"volume"`
QuoteAssetVolume float64       `json:"quoteAssetVolume"`
NumberOfTrades   float64       `json:"numberOfTrades"`
Calculations     []Calculation `gorm:"foreignKey:OhlcvRefer"`
}

type Calculation struct {
gorm.Model
OhlcvRefer uint   `gorm:"uniqueIndex:idx_calculation"`
Key        string `gorm:"uniqueIndex:idx_calculation"`
Config     string `gorm:"uniqueIndex:idx_calculation"`
Value      float64
}

如您所见,两个表都有唯一索引,以防止插入重复数据。第一个表foreignKey是第二个表唯一索引的一部分。问题是我如何处理ON冲突不做任何行为为两个表与一个单一的GORM创建语句?

在添加计算关联之前,我可以使用

处理CONFLICTS
err = db.Clauses(clause.OnConflict{DoNothing: true,
Columns: []clause.Column{{Name: "interval"}, {Name: "pair"}, {Name: "open_time"}, {Name: "close_time"}},
}).Create(ohlcvs).Error

但现在我得到以下错误:

错误:重复键值违反唯一约束&;idx_calculation&;(SQLSTATE 23505)

我需要的是什么都不做计算冲突。

要实现所需的功能,在这两个结构体上使用Unique索引约束应该就足够了。让我们看看如何实现它。

package main
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type User struct {
Id    int
Name  string `gorm:"uniqueIndex:idx_name"`
Posts []Post
}
type Post struct {
Id     int
Title  string `gorm:"uniqueIndex:idx_title"`
UserId int
}
func main() {
dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(&Post{})
db.AutoMigrate(&User{})
db.Create(&User{
Name: "john doe",
Posts: []Post{
{Title: "first"},
{Title: "second"}, // to generate an error change to "first"
},
})
}

通过这种方式,如果您输入重复的值,数据库本身将阻止您。这对users表和posts表都有效。在我看来,这是一种非常简洁的方法,你可以随心所欲地灵活使用。
让我知道这是否解决了你的问题或有其他东西!

最新更新