GO – Gin/Gorm/Postgresql – 创建一个具有“一对一”关联的外键

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

GO - Gin/Gorm/Postgresql - Create a foreignKey with "has one" association

问题

我已阅读文档(https://gorm.io/docs/has_one.html)并按照建议进行了测试,但我无法创建关联。我的表如下所示(名称为意大利语):

models/tables.go

type TeatroY struct {
    gorm.Model
    Nome  string
    Posti int
}

type SpettacoloXY struct {
    gorm.Model
    Nome   string
    Teatro TeatroY `gorm:"foreignKey:id"`
}

在主函数中,我使用了经典的 automigrate:

initializers.DB.AutoMigrate(&models.TeatroY{}, &models.SpettacoloXY{})

我得到的错误如下:

"2023/04/02 16:12:24 E:/Work/Mota/cdbp4/server.go:13 ERROR: relation
"spettacolo_xies" does not exist (SQLSTATE 42P01) [33.459ms] [rows:0]
ALTER TABLE "teatro_ies" ADD CONSTRAINT "fk_spettacolo_xies_teatro"
FOREIGN KEY ("id") REFERENCES "spettacolo_xies"("id")"

在创建一个 "TeatroY" 后,当我创建一个 "SpettacoloXY" 时,"Teatro" 字段必须与一个且仅与一个 "TeatroY" 关联。

提前感谢您的帮助。

英文:

I've read the documentation (https://gorm.io/docs/has_one.html) and tested as suggested but I can't create the association.
My tables look like this (the names are in Italian)

models/tables.go

type TeatroY struct {
	gorm.Model
	Nome  string
	Posti int
}

type SpettacoloXY struct {
	gorm.Model
	Nome   string
	Teatro TeatroY `gorm:"foreignKey:id"`
}

and in the main I use the classic automigrate

initializers.DB.AutoMigrate(&models.TeatroY{}, &models.SpettacoloXY{})

The error I get is as follows

> "2023/04/02 16:12:24 E:/Work/Mota/cdbp4/server.go:13 ERROR: relation
> "spettacolo_xies" does not exist (SQLSTATE 42P01) [33.459ms] [rows:0]
> ALTER TABLE "teatro_ies" ADD CONSTRAINT "fk_spettacolo_xies_teatro"
> FOREIGN KEY ("id") REFERENCES "spettacolo_xies"("id")"

After create a "TeatroY", when I create a "SpettacoloXY" the "Teatro" field must be associated with one and only one "TeatroY"

Thanks in advance for the help

答案1

得分: 1

将模型迁移代码更改为以下内容:

initializers.DB.AutoMigrate(&models.SpettacoloXY{}, &models.TeatroY{})

将消除错误,并在数据库中创建这两个表。

英文:

Changing the model migration code to this:

initializers.DB.AutoMigrate(&models.SpettacoloXY{}, &models.TeatroY{})

will get rid of the error and will create both tables in the database.

huangapple
  • 本文由 发表于 2023年4月2日 22:25:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75912612.html
匿名

发表评论

匿名网友

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

确定