我有 2 个结构有很多这样的关系:
type Domain struct {
ID uint `gorm:"primaryKey;type:serial"`
Emails []Email `gorm:"foreignKey:ID" "column:emails"`
}
type Email struct {
ID uint `gorm:"primaryKey;type:serial"`
Address string `gorm:"column:address"`
}
我在这里关注 gorm 文档:https ://gorm.io/docs/associations.html#Association-Mode
据我了解,当我们插入一条Domain记录时,gorm首先将数组电子邮件([]Email)插入数据库,我在尝试插入数据库时遇到了这样的问题:
var domain models.Domain
var emails []models.Email
for key, _ := range Output {
emails = append(emails, models.Email{Address: key})
}
domain = models.Domain{
Emails: emails,
}
dataAccess.Domain.Insert(domain) // db.Create(&domain)
这是我的控制台中的输出:
2020/09/10 10:37:46 /Users/tho/go/src/txxxx/exxxx/dataAccess/domains.go:18 ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time (SQLSTATE 21000)
[362.162ms] [rows:0] INSERT INTO "emails" ("address","id") VALUES ('info@example.com',2),('d.apple@example.com',2) ON CONFLICT ("id") DO UPDATE SET "id"="excluded"."id" RETURNING "id"
2020/09/10 10:37:46 /Users/tho/go/src/txxxx/exxxx/dataAccess/domains.go:18 ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time (SQLSTATE 21000)
[1078.499ms] [rows:1] INSERT INTO "domains" DEFAULT VALUES RETURNING "id"
ERRO[0050] Err: ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time (SQLSTATE 21000)
Gorm 插入 2 封具有相同 id 的电子邮件,因此 postresql 错误如上所示。我怎样才能避免相同的 id,因为它primaryKey已经serial存在(自动增量)。
慕虎7371278
相关分类