Skip to content

Instantly share code, notes, and snippets.

@islishude
Created August 18, 2019 08:13
Show Gist options
  • Save islishude/f326f8b5c55a17781f469ecf5e960681 to your computer and use it in GitHub Desktop.
Save islishude/f326f8b5c55a17781f469ecf5e960681 to your computer and use it in GitHub Desktop.
gorm-one2many-example
package main
import (
"fmt"
"log"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
// Student table
type Student struct {
gorm.Model
Name string `gorm:"not null"`
TeacherID uint
}
// Teacher table
type Teacher struct {
gorm.Model
Name string
Students []*Student
}
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(Student), new(Teacher))
db.Debug().Create(&Teacher{Name: "te_0"})
db.Debug().Create(&Student{Name: "st_0", TeacherID: 1})
db.Debug().Create(&Student{Name: "st_1", TeacherID: 1})
var t Teacher
if db.Debug().First(&t, 1).RecordNotFound() {
log.Fatal("Teacher not found")
}
db.Debug().Model(&t).Related(&t.Students)
for _, item := range t.Students {
fmt.Printf("%+v", item)
fmt.Println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment