Hello Gophers, Good Afternoon. Recently I come across an issue in GORM github.com/jinzhu/gorm. In the associations like One2One, One2Many and Many2Many this GORM is not adding the Foreign Key and so we need to add this foreign key relation manually. So anybody knows this how to do without manual work, let us know.
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
type Customer struct {
CustId int `gorm:"primary_key"`
CustomerName string
Contacts []Contact `gorm:"ForeignKey:CustId"`
}
type Contact struct {
ContactId int `gorm:"primary_key"`
CountryCode int
MobileNo uint
CustId int
}
func main() {
db, err := gorm.Open("mysql", "root:root@tcp(127.0.0.1:3306)/sample?charset=utf8&parseTime=True")
if err != nil {
panic(err.Error())
}
defer db.Close()
//db.DropTableIfExists(&Contact{}, &Customer{})
db.AutoMigrate(&Customer{}, &Contact{})
db.Model(&Contact{}).AddForeignKey("cust_id", "customers(cust_id)", "CASCADE", "CASCADE")
/* Here, I'm manually adding foreign key. It is not creating by GORM even if I write tag
`gorm:"ForeignKey:CustId"` in struct model as I have written in Customer struct */
Custs1 := Customer{CustomerName: "John", Contacts: []Contact{
{CountryCode: 91, MobileNo: 956112},
{CountryCode: 91, MobileNo: 997555}}}
Custs2 := Customer{CustomerName: "Martin", Contacts: []Contact{
{CountryCode: 90, MobileNo: 808988},
{CountryCode: 90, MobileNo: 909699}}}
db.Create(&Custs1)
db.Create(&Custs2)
}