Search code examples
mysqlgogo-gorm

Why does foreign key not get generated with GORM?


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?


Solution

  • I think you need:

    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.