-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelations.go
74 lines (67 loc) · 1.35 KB
/
relations.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
func relations() {
db, err := gorm.Open("postgres", "postgres://postgres@database?sslmode=disable")
if err != nil {
panic(fmt.Sprintf("failed to connect database: %v", err))
}
fmt.Println("connected the database")
defer db.Close()
// Migrate the schema
db.DropTableIfExists(&Product{})
db.DropTableIfExists(&Order{})
fmt.Println("dropped tables")
db.AutoMigrate(&Product{})
db.AutoMigrate(&Order{})
fmt.Println("created tables")
// Create
products := []Product{
Product{
Code: "L1212",
Price: 1000,
},
Product{
Code: "L1213",
Price: 2000,
},
}
for _, p := range products {
db.Create(&p)
}
db.Find(&products)
orders := []Order{
Order{
Status: "paid",
Product: products[0],
},
Order{
Status: "cancelled",
Product: products[1],
},
Order{
Status: "unpaid",
Product: products[1],
},
}
for _, o := range orders {
db.Create(&o)
}
var joinedOrders []Order
db.Preload("Product").Find(&joinedOrders)
for _, o := range orders {
fmt.Println(o.Status)
fmt.Printf("\t%s\n", o.Product.Code)
}
var joinedProducts []Product
db.Preload("Orders").Find(&joinedProducts)
for _, p := range joinedProducts {
fmt.Println(p.Code)
for _, o := range p.Orders {
fmt.Printf("\t%s\n", o.Status)
}
}
}