-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathgorm_cheat_sheet.go
63 lines (54 loc) · 1.28 KB
/
gorm_cheat_sheet.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
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
func main() {
type Product struct {
gorm.Model
Code string
Price int
}
db, err := gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", "postgres", "postgres", "gobyexample"))
if err != nil {
panic("failed to connect database")
}
defer db.Close()
// Migrate the schema
db.AutoMigrate(&Product{})
/*
Create
*/
db.Create(&Product{Code: "L1212", Price: int(100)})
db.Create(&Product{Code: "L1213", Price: int(100)})
// Read
var product Product
db.First(&product, 1) // find product with id 1
db.First(&product, "code = ?", "L1212") // find product with code l1212
// Update - update product's price to 2000
db.Model(&product).Update("Price", 2000)
/*
Select
*/
products := make([]Product, 0)
db.Select("code, price").Find(&products)
fmt.Println(products)
/*
Pluck
*/
codes := make([]string, 0)
db.Model(&Product{}).Pluck("code", &codes)
fmt.Println(codes)
/*
Group by code
*/
groupResult := new([]struct {
Code string `json:"code"`
Sum int `json:"sum"`
})
db.Table("products").Select("code, sum(price) as sum").Group("code").Scan(groupResult)
fmt.Println(groupResult)
// Delete - delete product
db.Delete(&product)
}