Created
June 1, 2016 11:01
-
-
Save stroborobo/74650f6fa9ffabf1f4c71f1d6364ee83 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"crypto/rand" | |
"fmt" | |
"log" | |
"math/big" | |
"github.com/jinzhu/gorm" | |
_ "github.com/lib/pq" | |
) | |
type Countdown struct { | |
ID int | |
Name string | |
OwnerID int | |
OwnerType string | |
} | |
type ShopCountdown struct { | |
ID int | |
Name string | |
Countdowns []*Countdown `gorm:"polymorphic:Owner;"` | |
} | |
func main() { | |
db, err := gorm.Open("postgres", "host=/tmp database=test") | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer db.Close() | |
db.LogMode(true) | |
db.AutoMigrate(&Countdown{}, &ShopCountdown{}) | |
//if err := create(db); err != nil { | |
// log.Fatalln(err) | |
//} | |
if err := load(db); err != nil { | |
log.Fatalln(err) | |
} | |
} | |
func create(db *gorm.DB) error { | |
sc := &ShopCountdown{Name: "Mein geiler Shop"} | |
if err := db.Preload("Countdowns").FirstOrCreate(sc, sc).Error; err != nil { | |
return err | |
} | |
randBigInt, err := rand.Int(rand.Reader, big.NewInt(1000)) | |
if err != nil { | |
return err | |
} | |
log.Println("shop loaded: ", sc) | |
sc.Countdowns = append(sc.Countdowns, &Countdown{Name: fmt.Sprintf("CD %d", randBigInt.Int64())}) | |
if err := db.Save(sc).Error; err != nil { | |
return err | |
} | |
log.Println("shop saved: ", sc) | |
return nil | |
} | |
func load(db *gorm.DB) error { | |
sc := &ShopCountdown{Name: "Mein geiler Shop"} | |
if err := db.Model(sc).Where(sc).Preload("Countdowns").First(sc).Error; err != nil { | |
return err | |
} | |
log.Println(sc) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment