问题
I am trying to create a foreign key on the Password table which must point to the id column inside the User table. But as I try the following, it does not work. The foreign key is not generated. It simply adds the column name user_id inside the password table.
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{})
}
What am I doing wrong? How could I make a foreign key inside Password table pointing to User table?
来源:https://stackoverflow.com/questions/59836572/why-does-foreign-key-not-get-generated-with-gorm