Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json"
- "fmt"
- "github.com/jinzhu/gorm"
- _ "github.com/jinzhu/gorm/dialects/postgres"
- )
- type Brand struct {
- gorm.Model
- Name string
- Description string
- Image int
- CreationYear int
- EndYear int
- Country string
- }
- type Bike struct {
- // add basic ID/Created@/Updated@/Delete@ through Gorm
- gorm.Model
- Name string
- Brand Brand
- BrandID int `json:"-"`
- Year string
- Description string
- Images []Image `gorm:"many2many:bike_images;"`
- }
- type Image struct {
- gorm.Model
- Name string
- Path string
- Type string
- }
- var (
- DB *gorm.DB
- )
- func initDB() (DB *gorm.DB) {
- DB, err := gorm.Open("postgres", fmt.Sprintf(
- "user=%s password='%s' host=%s dbname=%s",
- "test",
- "test",
- "//var/run/postgresql",
- "test"))
- if err != nil {
- fmt.Println("error:", err)
- }
- // Debug Mode
- DB.LogMode(true)
- DB.DropTable(&Image{}, &Brand{}, &Bike{})
- DB.CreateTable(&Image{}, &Brand{}, &Bike{})
- DB.Model(&Bike{}).AddUniqueIndex("bike_uniqueness", "name, year, brand_id")
- DB.Model(&Image{}).AddUniqueIndex("image_uniqueness", "name", "path")
- DB.AutoMigrate(&Bike{}, &Image{}, &Brand{})
- return
- }
- func (img *Image) Save() {
- if DB.NewRecord(img) {
- oldi := new(Image)
- DB.Where("name = ?", img.Name).First(oldi)
- if oldi.ID == 0 && oldi.Name == "" {
- fmt.Println("Recording the New Image")
- DB.Create(img)
- } else {
- fmt.Println("Updating The Image Record")
- DB.Model(oldi).Updates(img)
- img = oldi
- }
- } else {
- fmt.Printf("Saving Image %#v\n", *img)
- DB.Save(img)
- }
- fmt.Printf("Saved Image %#v\n", *img)
- }
- func main() {
- DB = initDB()
- // We receive a JSON with No ID (Some of the element already Exists)
- var inputImage = []byte(`
- {
- "Name":"34FDF234.jpg",
- "Path":"uploads/34FDF234.jpg"
- }
- `)
- var inputBike = []byte(`
- {
- "Name":" Da Bike",
- "Description":"SUper Description ",
- "Brand":{
- "Name":"Trek"
- },
- "Images":[
- {
- "Name":"34FDF234.jpg",
- "Path":"uploads/34FDF234.jpg"
- },
- {
- "Name":"8404VRVRG01.jpg",
- "Path":"uploads/8404VRVRG01.jpg"
- }
- ]
- }`)
- // Unmarshal Image
- var image Image
- err := json.Unmarshal(inputImage, &image)
- if err != nil {
- fmt.Println("error:", err)
- }
- // Unmarshal Bike
- var bike Bike
- err = json.Unmarshal(inputBike, &bike)
- if err != nil {
- fmt.Println("error:", err)
- }
- fmt.Printf("Will Create the Image Record %v\n", image)
- DB.Create(&image)
- fmt.Printf("Image Created within the Database %v\n", image)
- // Create the Bike Record
- for i := range bike.Images {
- bike.Images[i].Save()
- }
- fmt.Printf("Will Create the Bike Record %#v\n", bike)
- DB.Set("gorm:save_associations", false).Create(&bike)
- DB.Save(&bike)
- fmt.Printf("Bike Saved %v\n", bike)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement