Skip to content

Instantly share code, notes, and snippets.

@WangYihang
Created July 31, 2018 10:23
Show Gist options
  • Save WangYihang/7d43d70db432ff8f3a0a88425bfca7f2 to your computer and use it in GitHub Desktop.
Save WangYihang/7d43d70db432ff8f3a0a88425bfca7f2 to your computer and use it in GitHub Desktop.
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/satori/go.uuid"
"fmt"
)
type Email struct {
ID uuid.UUID `gorm:"primary_key;type:char(36);"`
Address string
Uid uuid.UUID
}
type User struct {
ID uuid.UUID `gorm:"primary_key;type:char(36);"`
Name string
Emails []Email `gorm:"ForeignKey:Uid"`
}
func main() {
// Connect
db, err := gorm.Open("mysql", "root:root@/test?charset=utf8&parseTime=True&loc=Local")
if err != nil {
fmt.Println("failed to connect database")
}
defer db.Close()
// Migrate
db.AutoMigrate(
&User{},
&Email{},
)
/*
id, err := uuid.FromString("0ff7a01f-9ab6-4041-b372-4375ce3d4065")
// Create user
db.Debug().Create(
&User{
ID:id,
Name: "admin",
Emails: []Email{
{
ID:uuid.Must(uuid.NewV4()),
Address: "[email protected]",
Uid: id,
},
{
ID:uuid.Must(uuid.NewV4()),
Address: "[email protected]",
Uid: id,
},
},
},
)
/*
// Get user id
id, err := uuid.FromString("0ff7a01f-9ab6-4041-b372-4375ce3d4065")
if err != nil {
fmt.Println("parse uuid failed")
}
// Create emails
emails := []Email {
{
ID:uuid.Must(uuid.NewV4()),
Address: "[email protected]",
Uid: id,
},
{
ID:uuid.Must(uuid.NewV4()),
Address: "[email protected]",
Uid: id,
},
}
fmt.Println(emails)
for _, email := range emails{
db.Debug().Create(email)
}
*/
var user User
err = db.Debug().Where(&User{Name: "admin"}).First(&user).Error
if err != nil {
fmt.Println("Query failed")
}
fmt.Println(user)
var emails []Email
err = db.Debug().Model(&user).Related(&emails, "Emails").Error
if err != nil {
fmt.Println("Query failed")
}
fmt.Println(emails)
user.Emails = emails
fmt.Println(user)
/*
var email Email
err = db.Debug().Where(&Email{Address: "[email protected]"}).First(&email).Error
if err != nil {
fmt.Println("Query failed")
}
fmt.Println(email)
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment