Postgresql gorm中的外键和关联未正确创建
我尝试在PostgreSQL上为它所属的人和数据所属的人创建模型关联ForeignKey 这是我的结构Postgresql gorm中的外键和关联未正确创建,postgresql,go,go-gorm,go-gin,Postgresql,Go,Go Gorm,Go Gin,我尝试在PostgreSQL上为它所属的人和数据所属的人创建模型关联ForeignKey 这是我的结构 type ( Data struct { ID uint `gorm:"auto_increment"` PersonID uint Person *Person `gorm:"foreignkey:id;association_foreignkey:PersonID"` Birthday
type (
Data struct {
ID uint `gorm:"auto_increment"`
PersonID uint
Person *Person `gorm:"foreignkey:id;association_foreignkey:PersonID"`
Birthday *time.Time
Salary float64 `gorm:"type:money"`
}
Person struct {
gorm.Model
Email string `gorm:"type:varchar(100);unique_index;not null"`
Password string `gorm:"type:varchar(100);not null"`
Role string `gorm:"type:varchar(30);not null"`
DataID uint
Data *Data `gorm:"foreignkey:id;association_foreignkey:DataID"`
}
)
我希望数据表上的
Person\u id
是Person表中的外键,并且在我的DBeaver上看到ER图后,Person表上的Data\u id
是数据表中的外键,这些不是我希望创建的:(在ER图上没有任何关系,我确信我在上面的关联是错误的,有人能给我一些信息来解决这个问题吗?当您自动迁移数据库时,您可以使用gorm的函数来解决这个问题
db.Model(&Data{}).AddForeignKey("person", "person(id)", "NO ACTION", "NO ACTION")
db.Model(&Person{}).AddForeignKey("data", "data(id)", "NO ACTION", "NO ACTION")
您也可以检查这一点:当您自动迁移数据库时,您可以使用gorm的函数
db.Model(&Data{}).AddForeignKey("person", "person(id)", "NO ACTION", "NO ACTION")
db.Model(&Person{}).AddForeignKey("data", "data(id)", "NO ACTION", "NO ACTION")
您也可以检查这一点: