Why does foreign key not get generated with GORM?

三世轮回 提交于 2020-01-25 10:13:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!