英文:
Gorm element collections
问题
我正在开发一个按地区存储山脉的应用程序。
type Mountain struct {
Name string
Height int
RegionID int
}
type Region struct {
ID int64
Name string
Mountains []Mountain
}
正如你所看到的,我有一个山脉数组,其中RegionID
有一个外键约束。我故意不设置山脉的ID,以便在更新时完全替换它们。
当我尝试保存地区时:
var region = &models.Region{
Name: "Lombardia",
Mountains: []models.Mountain{
{
Name: "Pizzo Coca",
Height: 3050,
},
{
Name: "Bernina",
Height: 4049,
},
},
}
db.Create(region)
我遇到了这个错误:
ERROR: ON CONFLICT DO UPDATE requires inference specification or constraint name
(SQLSTATE 42601)
我知道这不是英文,但我在网上找不到英文版本。
英文:
I'm working on an application that stores mountains by region.
type Mountain struct {
Name string
Height int
RegionID int
}
type Region struct {
ID int64
Name string
Mountains []Mountain
}
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:
var region = &models.Region{
Name: "Lombardia",
Mountains: []models.Mountain{
{
Name: "Pizzo Coca",
Height: 3050,
},
{
Name: "Bernina",
Height: 4049,
},
},
}
db.Create(region)
I have this error:
ERRORE: ON CONFLICT DO UPDATE richiede una specifica di inferenza o il nome di un vincolo
(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,例如:
import "gorm.io/gorm/clause"
// 在冲突时不执行任何操作
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&user)
有关更多信息,请参阅此文章。
英文:
Try using the Upsert / On Conflict, as example:
import "gorm.io/gorm/clause"
// Do nothing on conflict
db.Clauses(clause.OnConflict{DoNothing: true}).Create(&user)
Some info in this article
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论