亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 GORM 不能生成外鍵?

為什么 GORM 不能生成外鍵?

Go
滄海一幻覺 2022-05-05 18:13:19
我正在嘗試在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")

讓我知道這是否有幫助。


查看完整回答
反對 回復 2022-05-05
?
慕容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"`

}


查看完整回答
反對 回復 2022-05-05
  • 2 回答
  • 0 關注
  • 284 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號