为什么 GORM 不生成外键?
Why does foreign key not get generated with GORM?
我正在尝试在 Password
table 上创建外键,它必须指向 User
table 内的 id
列。但是当我尝试以下操作时,它不起作用。 foreign key
未生成。它只是在 password
table.
中添加列名 user_id
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
table 中创建指向 User
table 的外键?
我认为你需要:
db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
我像这样把我的放在自动迁移语句之后
db.AutoMigrate(&User{}, &Password{})
db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
如果有帮助请告诉我。
试试这个。
type Password struct {
gorm.Model
Password string `gorm:"not null"`
UserId int `gorm:"not null"`
User User `gorm:"foreignkey:UserId;references:id"`
}
我正在尝试在 Password
table 上创建外键,它必须指向 User
table 内的 id
列。但是当我尝试以下操作时,它不起作用。 foreign key
未生成。它只是在 password
table.
user_id
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
table 中创建指向 User
table 的外键?
我认为你需要:
db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
我像这样把我的放在自动迁移语句之后
db.AutoMigrate(&User{}, &Password{})
db.Model(&Password{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
如果有帮助请告诉我。
试试这个。
type Password struct {
gorm.Model
Password string `gorm:"not null"`
UserId int `gorm:"not null"`
User User `gorm:"foreignkey:UserId;references:id"`
}