我正在嘗試在Password表上創建一個外鍵,該外鍵必須指向表id內的User列。但是當我嘗試以下操作時,它不起作用。foreign key沒有生成。user_id它只是在表中添加列名password。package schemaimport ("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表的外鍵?
2 回答

波斯汪
TA貢獻1811條經驗 獲得超4個贊
我認為你需要:
db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
我把我的放在我的自動遷移語句之后
db.AutoMigrate(&User{}, &Password{})
db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
讓我知道這是否有幫助。

慕容708150
TA貢獻1831條經驗 獲得超4個贊
試試這個。
type Password struct {
gorm.Model
Password string `gorm:"not null"`
UserId int `gorm:"not null"`
User User `gorm:"foreignkey:UserId;references:id"`
}
- 2 回答
- 0 關注
- 284 瀏覽
添加回答
舉報
0/150
提交
取消