Skip to content

Instantly share code, notes, and snippets.

@islishude
Created August 18, 2019 08:28
Show Gist options
  • Save islishude/367d84d7c0849e6b221829263514b889 to your computer and use it in GitHub Desktop.
Save islishude/367d84d7c0849e6b221829263514b889 to your computer and use it in GitHub Desktop.
gorm_one2one_example
package main
import (
"fmt"
"log"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
// User table
type User struct {
gorm.Model
Password string `gorm:"type:varchar(20);not null"`
}
// Profile table
type Profile struct {
gorm.Model
User User
UserID uint
Birthday time.Time
}
func main() {
db, err := gorm.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?parseTime=true")
if err != nil {
log.Fatalln("failed to connect database", err)
}
defer db.Close()
db.SingularTable(true)
db.Debug().AutoMigrate(new(User), new(Profile))
userInfo := User{Password: "password"}
profileInfo := Profile{User: userInfo, Birthday: time.Now()}
// create user and profile together
db.Debug().Create(&profileInfo)
var u User
u.ID = 1
var p Profile
// get user info and profile
db.Debug().Model(&u).Related(&p)
fmt.Printf("%+v", p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment