-
-
Notifications
You must be signed in to change notification settings - Fork 404
/
example_many2many_test.go
107 lines (92 loc) · 2.33 KB
/
example_many2many_test.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package pg_test
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
)
func init() {
// Register many to many model so ORM can better recognize m2m relation.
// This should be done before dependant models are used.
orm.RegisterTable((*OrderToItem)(nil))
}
type Order struct {
Id int
Items []Item `pg:"many2many:order_to_items"`
}
type Item struct {
Id int
}
type OrderToItem struct {
OrderId int
ItemId int
}
func ExampleDB_Model_manyToMany() {
db := connect()
defer db.Close()
if err := createManyToManyTables(db); err != nil {
panic(err)
}
values := []interface{}{
&Item{Id: 1},
&Item{Id: 2},
&Order{Id: 1},
&OrderToItem{OrderId: 1, ItemId: 1},
&OrderToItem{OrderId: 1, ItemId: 2},
}
for _, v := range values {
_, err := db.Model(v).Insert()
if err != nil {
panic(err)
}
}
// Select order and all items with following queries:
//
// SELECT "order"."id" FROM "orders" AS "order" ORDER BY "order"."id" LIMIT 1
//
// SELECT order_to_items.*, "item"."id" FROM "items" AS "item"
// JOIN order_to_items AS order_to_items ON (order_to_items."order_id") IN (1)
// WHERE ("item"."id" = order_to_items."item_id")
order := new(Order)
err := db.Model(order).Relation("Items").First()
if err != nil {
panic(err)
}
fmt.Println("Order", order.Id, "Items", order.Items[0].Id, order.Items[1].Id)
// Select order and all items sorted by id with following queries:
//
// SELECT "order"."id" FROM "orders" AS "order" ORDER BY "order"."id" LIMIT 1
//
// SELECT order_to_items.*, "item"."id" FROM "items" AS "item"
// JOIN order_to_items AS order_to_items ON (order_to_items."order_id") IN (1)
// WHERE ("item"."id" = order_to_items."item_id")
// ORDER BY item.id DESC
order = new(Order)
err = db.Model(order).
Relation("Items", func(q *pg.Query) (*pg.Query, error) {
q = q.OrderExpr("item.id DESC")
return q, nil
}).
First()
if err != nil {
panic(err)
}
fmt.Println("Order", order.Id, "Items", order.Items[0].Id, order.Items[1].Id)
// Output: Order 1 Items 1 2
// Order 1 Items 2 1
}
func createManyToManyTables(db *pg.DB) error {
models := []interface{}{
(*Order)(nil),
(*Item)(nil),
(*OrderToItem)(nil),
}
for _, model := range models {
err := db.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: true,
})
if err != nil {
return err
}
}
return nil
}