Gorm元素集合

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

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

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:

确定