'Go_gorm: AutoMigrate with foreignKey( Failed to open the referenced table )

I've just entered stuyding Go language and try to use gorm connecting w MySQL.

When I try to create tables with foreign key, it gives me same error "Error 1824: Failed to open the referenced table" or just not create Foreign Keys.

here's my code.

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/logger"
)

//======TeamServer======
func main() {
    dsn := "```serverinfo```"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
        Logger: logger.Default.LogMode(logger.Info),
    })
    if err != nil {
        panic(err)
    }

    type Dept struct {
        DeptID    uint `gorm:"primaryKey"`
        DeptName  string
        DeptBuild string
    }
    type Prof struct {
        ProfID  uint `gorm:"primaryKey"`
        Name    string
        Age     int
        Gender  string
        Country string 
        Dept    Dept   `gorm:"foreignKey:DeptID"`
    }
    type Student struct {
        StuID   uint `gorm:"primaryKey"`
        Name    string
        Age     int
        Gender  string
        Country string 
        Dept    Dept   `gorm:"foreignKey:DeptID"`
    }

    //create Tables
    db.AutoMigrate(&Dept{}, &Prof{}, &Student{})

}
    



Solution 1:[1]

Did you put a real dsn instead of "serverinfo"? as in https://gorm.io/docs/connecting_to_the_database.html#MySQL

Does your error occur at gorm.Open? or at the migration where you did not wrap the error.

err:=db.AutoMigrate(&Dept{}, &Prof{}, &Student{})
if err!= nil {
  panic(err)
}

You could also vary the order of the structs within the automigrate function, although that should not change much within the same transaction.

If that still not works you could set the PK to be ID:

type Dept struct {
    ID        uint
    DeptName  string
    DeptBuild string
}
type Prof struct {
    ProfID  uint `gorm:"primaryKey"`
    Name    string
    Age     int
    Gender  string
    Country string
    DeptID  uint
    Dept    Dept
}
type Student struct {
    StuID   uint `gorm:"primaryKey"`
    Name    string
    Age     int
    Gender  string
    Country string
    DeptID  uint
    Dept    Dept
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1