Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- }
Add Comment
Please, Sign In to add comment