Created
May 22, 2018 11:11
-
-
Save jtbonhomme/ff6db22b8dcac7dd9349e26bad002fb1 to your computer and use it in GitHub Desktop.
Gorm example of foreign key definition for a hasMany relation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
Thanks, your codes so helpful