SHARE
TWEET

Untitled

a guest May 26th, 2018 87 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "github.com/jinzhu/gorm"
  6.     _ "github.com/jinzhu/gorm/dialects/postgres"
  7. )
  8.  
  9. // Customer ...
  10. type Customer struct {
  11.     CustID       int `gorm:"primary_key"`
  12.     CustomerName string
  13.     Contacts     []Contact `gorm:"ForeignKey:CustID"`
  14. }
  15.  
  16. // Contact ...
  17. type Contact struct {
  18.     ContactID   int `gorm:"primary_key"`
  19.     CountryCode int
  20.     MobileNo    uint
  21.     CustID      int
  22. }
  23.  
  24. func main() {
  25.     db, err := gorm.Open("postgres", "user=intercloud password=intercloud dbname=intercloud sslmode=disable")
  26.     if err != nil {
  27.         panic(err.Error())
  28.     }
  29.     defer db.Close()
  30.     db.DropTableIfExists(&Contact{}, &Customer{})
  31.     db.AutoMigrate(&Customer{}, &Contact{})
  32.     db.Model(&Contact{}).AddForeignKey("cust_id", "customers(cust_id)", "CASCADE", "CASCADE")
  33.  
  34.     /* Here, I'm manually adding foreign key. It is not creating by GORM even if I write tag
  35.        `gorm:"ForeignKey:CustID"` in struct model  as I have written in Customer struct    */
  36.  
  37.     Custs1 := Customer{CustomerName: "John", Contacts: []Contact{
  38.         {CountryCode: 91, MobileNo: 956112},
  39.         {CountryCode: 91, MobileNo: 997555}}}
  40.  
  41.     Custs2 := Customer{CustomerName: "Martin", Contacts: []Contact{
  42.         {CountryCode: 90, MobileNo: 808988},
  43.         {CountryCode: 90, MobileNo: 909699}}}
  44.     db.Create(&Custs1)
  45.     db.Create(&Custs2)
  46.  
  47.     cust := []Customer{}
  48.     db.Debug().Where("customer_name=?", "Martin").Preload("Contacts").Find(&cust)
  49.  
  50.     fmt.Println(cust)
  51. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top