Skip to content

Instantly share code, notes, and snippets.

@jtbonhomme
Created May 22, 2018 11:11
Show Gist options
  • Save jtbonhomme/ff6db22b8dcac7dd9349e26bad002fb1 to your computer and use it in GitHub Desktop.
Save jtbonhomme/ff6db22b8dcac7dd9349e26bad002fb1 to your computer and use it in GitHub Desktop.
Gorm example of foreign key definition for a hasMany relation
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
// Customer ...
type Customer struct {
CustID int `gorm:"primary_key"`
CustomerName string
Contacts []Contact `gorm:"ForeignKey:CustID"`
}
// Contact ...
type Contact struct {
ContactID int `gorm:"primary_key"`
CountryCode int
MobileNo uint
CustID int
}
func main() {
db, err := gorm.Open("postgres", "user=intercloud password=intercloud dbname=intercloud sslmode=disable")
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)
cust := []Customer{}
db.Debug().Where("customer_name=?", "Martin").Preload("Contacts").Find(&cust)
fmt.Println(cust)
}
@arismudri
Copy link

arismudri commented Oct 2, 2020

Thanks, your codes so helpful

@krisnadwipayana07
Copy link

krisnadwipayana07 commented Sep 26, 2021

can we just create contact and add it to the customer?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment