【问题标题】:Postgresql Has-Many relationship insert same id errorPostgresql Has-Many 关系插入相同的 id 错误
【发布时间】:2020-09-10 05:18:18
【问题描述】:

我有 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 (autoIncrement)。

【问题讨论】:

    标签: postgresql go go-gorm


    【解决方案1】:

    你需要改变

    Emails []Email `gorm:"foreignKey:ID" "column:emails"`
    

    Emails []Email `gorm:"foreignKey:DomainId" "column:domain_id"`
    

    并添加

    DomainId uint   `gorm:"column:domain_id"`
    

    type Email struct

    试试:

    type Domain struct {
        ID     uint    `gorm:"primaryKey;type:serial"`
        Domain string  `gorm:"column:domain"`
        Emails []Email `gorm:"foreignKey:DomainId" "column:domain_id"`
    }
    
    type Email struct {
        ID       uint   `gorm:"primaryKey;type:serial"`
        Address  string `gorm:"column:address"`
        DomainId uint   `gorm:"column:domain_id"`
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      相关资源
      最近更新 更多