Golang GORM is not creating ForeignKey relationship

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)
                              }

Maybe caused by an open issue - see this comment.

Edited to add: Relevant statement from the comment:

Foreign keys dont seem to be generated through any means other than manually (through Model().AddForeignKey()).

Thank you for the reply Mr. christophberger. That means it is an open issue we have to add the foreign keys manually. One more question, did you know how to deal with the callbacks? I recently went through the library and documentation but didn’t get it clearly. Here is the link http://jinzhu.me/gorm/callbacks.html
So if you know kindly reply with some example.

I am afraid I have no examples at hand. In fact, the first time I looked into this ORM library was two days ago after reading your post! :slight_smile:

The documentation seems to consist mostly of code snippets, which makes it indeed not easy to understand.

Regarding the callbacks documentation: to me this looks as if you only need to define the desired callback function as a method of your model struct, and GORM then invokes the callback function at the relevant occasion(s). At the very bottom of the callbacks doc page there are a few (very short) examples.

Thank you Mr. Christophberger.

Any time! :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.