Gorm元素集合

huangapple go评论122阅读模式
英文:

Gorm element collections

问题

我正在开发一个按地区存储山脉的应用程序。

  1. type Mountain struct {
  2. Name string
  3. Height int
  4. RegionID int
  5. }
  6. type Region struct {
  7. ID int64
  8. Name string
  9. Mountains []Mountain
  10. }

正如你所看到的,我有一个山脉数组,其中RegionID有一个外键约束。我故意不设置山脉的ID,以便在更新时完全替换它们。

当我尝试保存地区时:

  1. var region = &models.Region{
  2. Name: "Lombardia",
  3. Mountains: []models.Mountain{
  4. {
  5. Name: "Pizzo Coca",
  6. Height: 3050,
  7. },
  8. {
  9. Name: "Bernina",
  10. Height: 4049,
  11. },
  12. },
  13. }
  14. db.Create(region)

我遇到了这个错误:

  1. ERROR: ON CONFLICT DO UPDATE requires inference specification or constraint name
  2. (SQLSTATE 42601)

我知道这不是英文,但我在网上找不到英文版本。

英文:

I'm working on an application that stores mountains by region.

  1. type Mountain struct {
  2. Name string
  3. Height int
  4. RegionID int
  5. }
  6. type Region struct {
  7. ID int64
  8. Name string
  9. Mountains []Mountain
  10. }

As you may see, I have an array of mountains with a foreign key constraint on RegionID. I'm trying on purpose to avoid setting ID on the mountains, in order to have them fully replaced when updating.

When I try to save the region:

  1. var region = &models.Region{
  2. Name: "Lombardia",
  3. Mountains: []models.Mountain{
  4. {
  5. Name: "Pizzo Coca",
  6. Height: 3050,
  7. },
  8. {
  9. Name: "Bernina",
  10. Height: 4049,
  11. },
  12. },
  13. }
  14. db.Create(region)

I have this error:

  1. ERRORE: ON CONFLICT DO UPDATE richiede una specifica di inferenza o il nome di un vincolo
  2. (SQLSTATE 42601)

I know that is not in english, but I can't find the english version on the net.

答案1

得分: 1

尝试使用Upsert / On Conflict,例如:

  1. import "gorm.io/gorm/clause"
  2. // 在冲突时不执行任何操作
  3. db.Clauses(clause.OnConflict{DoNothing: true}).Create(&user)

有关更多信息,请参阅此文章

英文:

Try using the Upsert / On Conflict, as example:

  1. import "gorm.io/gorm/clause"
  2. // Do nothing on conflict
  3. db.Clauses(clause.OnConflict{DoNothing: true}).Create(&user)

Some info in this article

huangapple
  • 本文由 发表于 2021年10月26日 16:46:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/69720070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定