Search code examples
gogo-gormrevel

Go migration doesn't create a foreign key


My first day with Go. I try to develop a migration mechanism with GORM within Revel.

These are my model structs:

type Role struct {
    gorm.Model
    Name string
}

type User struct {
    gorm.Model
    Name string
    Role Role  `gorm:"foreignkey:RoleIdForRole;association_foreignkey:Id"`
}

I simply automigrate both structs as follows, which work fine. I see tables called users and roles but users table doesn't have a field role_id or roleID

db.AutoMigrate(&models.Role{})
db.AutoMigrate(&models.User{})

What am I missing?


Solution

  • I found a solution.

    First of all, although Tim Brown's answer is a valid answer compatible with documentation, it doesn't work. As mentioned in many forum posts and github issues, GORM foreign key is not autogenerated as told in the documentation.

    But this helps:

    db.Model(&models.User{}).AddForeignKey("role_id", "roles(id)", "RESTRICT", "RESTRICT")
    

    Shortly you need to set foreign keys just after migrating the tables.