-
-
Save tonidy/a93dc85879572b483e24c968a0a47cd5 to your computer and use it in GitHub Desktop.
Gorm example of foreign key definition for a hasMany relation
This file contains hidden or 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment