我正在尝试在Password表上创建一个外键,该键必须指向表id内的User列。但是当我尝试以下操作时,它不起作用。将foreign key不会产生。它只是user_id在password表内添加列名。
Password
id
User
foreign key
user_id
password
package schema import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type User struct { gorm.Model FirstName string `gorm:"not null"` LastName string `gorm:"not null"` Email string `gorm:"type:varchar(100);unique_index"` IsActive bool `gorm:"not null"` IsVerified bool `gorm:"not null"` } type Password struct { gorm.Model Password string `gorm:"not null"` UserId int `gorm:"not null"` User User `gorm:"foreignkey:UserId;association_foreignkey:id"` } func SyncDB(db *gorm.DB) { db.AutoMigrate(&User{}) db.AutoMigrate(&Password{}) }
我究竟做错了什么?如何在Password表内部使外键指向User表?
我认为您需要:
db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
我把我的自动迁移声明放在这样
db.AutoMigrate(&User{}, &Password{}) db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
让我知道是否有帮助。