为什么GORM无法生成外键? [英] Why does foreign key not get generated with GORM?
本文介绍了为什么GORM无法生成外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 Password
表上创建一个外键,该外键必须指向 User
表内的 id
列.但是,当我尝试以下操作时,它不起作用.外键
不会生成.只需在 password
表内添加列名 user_id
.
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{})
}
我做错了什么?如何在 Password
表内制作指向 User
表的外键?
What am I doing wrong? How could I make a foreign key inside Password
table pointing to User
table?
推荐答案
我认为您需要:
db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
我在我的自动迁移语句之后放了我的
I put mine after my auto migrate statement like so
db.AutoMigrate(&User{}, &Password{})
db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
让我知道这是否有帮助.
Let me know if this helps.
这篇关于为什么GORM无法生成外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文