Skip to content

Instantly share code, notes, and snippets.

@nielvid
Forked from jtbonhomme/hasMany.go
Created June 7, 2022 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielvid/a791db3138c2d0d6e96485fdeb3246da to your computer and use it in GitHub Desktop.
Save nielvid/a791db3138c2d0d6e96485fdeb3246da 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment