Skip to content

Instantly share code, notes, and snippets.

@tboerger
Created March 11, 2016 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tboerger/49b678e8ff8b32c5a515 to your computer and use it in GitHub Desktop.
Save tboerger/49b678e8ff8b32c5a515 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type Packs []*Pack
type Pack struct {
ID uint `json:"id" gorm:"primary_key"`
Name string `json:"name" sql:"unique_index"`
Builds *Builds `json:"builds"`
}
type Builds []*Build
type Build struct {
ID uint `json:"id" gorm:"primary_key"`
Pack *Pack `json:"-"`
PackID uint `json:"pack_id" sql:"index"`
Name string `json:"name" sql:"unique_index"`
Mods *Mods `json:"mods" gorm:"many2many:build_mods;"`
}
func main() {
db, err := gorm.Open("sqlite3", "database.sqlite3")
if err != nil {
panic(err)
}
db.LogMode(true)
db.AutoMigrate(&Pack{}, &Build{})
pack1 := &Pack{Name: "Pack1"}
db.Create(pack1)
pack2 := &Pack{Name: "Pack2"}
db.Create(pack2)
pack3 := &Pack{Name: "Pack3"}
db.Create(pack3)
build1 := &Build{Name: "Build1", Pack: pack1}
db.Create(build1)
build2 := &Build{Name: "Build2", Pack: pack1}
db.Create(build2)
build3 := &Build{Name: "Build3", Pack: pack1}
db.Create(build3)
packs := &Packs{}
if err := db.Preload("Builds").Find(packs).Error; err != nil {
fmt.Printf("Failed to fetch packs. ", err)
return
}
fmt.Println(packs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment