Skip to content

Instantly share code, notes, and snippets.

@aalvesjr
Last active May 19, 2017 15:02
Show Gist options
  • Save aalvesjr/263c515d0706ad7de2c9d9a79169e24b to your computer and use it in GitHub Desktop.
Save aalvesjr/263c515d0706ad7de2c9d9a79169e24b to your computer and use it in GitHub Desktop.
[Golang] Relacionamento com GORM
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
type Manufacturer struct {
gorm.Model
BrandName string `json:"brand_name"`
Products []Product
}
type Product struct {
gorm.Model
Name string `json:"name"`
ManufacturerID uint `sql:"manufacturer_id" json:"manufacturer_id"`
Manufacturer Manufacturer
}
func main() {
URLDatabase := "postgresql://postgres:@localhost/gormtest?sslmode=disable"
db, err := gorm.Open("postgres", URLDatabase)
if err != nil {
panic(err)
}
defer db.Close()
db.AutoMigrate(&Manufacturer{})
db.AutoMigrate(&Product{})
m := Manufacturer{BrandName: "Teste Manufacturer"}
db.Create(&m)
p := Product{Name: "Product Test", ManufacturerID: m.ID}
// or could be:
// p := Product{Name: "Product Test", Manufacturer: m}
db.Create(&p)
product := Product{}
db.Preload("Manufacturer").First(&product, p.ID)
fmt.Println("Product:", product.Name)
// => Product: Product Test
fmt.Println("Manufacturer of product:", product.Manufacturer.BrandName)
// => Manufacturer of product: Teste Manufacturer
manufacturer := Manufacturer{}
db.Preload("Products").First(&manufacturer, m.ID)
fmt.Println("Manufacturer:", manufacturer.BrandName)
// => Manufacturer: Teste Manufacturer
fp := manufacturer.Products[0]
fmt.Println("First product:", fp.Name)
// => First product: Product Test
}
/*
// SCHEMA
gormtest=# \d manufacturers
Table "public.manufacturers"
Column | Type | Modifiers
------------+--------------------------+------------------------------------------------------------
id | integer | not null default nextval('manufacturers_id_seq'::regclass)
created_at | timestamp with time zone |
updated_at | timestamp with time zone |
deleted_at | timestamp with time zone |
brand_name | text |
Indexes:
"manufacturers_pkey" PRIMARY KEY, btree (id)
"idx_manufacturers_deleted_at" btree (deleted_at)
gormtest=# \d products
Table "public.products"
Column | Type | Modifiers
-----------------+--------------------------+-------------------------------------------------------
id | integer | not null default nextval('products_id_seq'::regclass)
created_at | timestamp with time zone |
updated_at | timestamp with time zone |
deleted_at | timestamp with time zone |
name | text |
manufacturer_id | integer |
Indexes:
"products_pkey" PRIMARY KEY, btree (id)
"idx_products_deleted_at" btree (deleted_at)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment