英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论