forked from betty200744/ultimate-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgorm_query_build.go
47 lines (42 loc) · 866 Bytes
/
gorm_query_build.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
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
var (
Dbuser = "postgres"
Dbpwd = "postgres"
Dbname = "gobyexample"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func Find(db *gorm.DB, code string, price int, order string) *gorm.DB {
q := db.Model(&Product{})
if code != "" {
q = q.Where("code = ?", code)
}
if price != 0 {
q = q.Where("price = ?", price)
}
if order != "" {
q = q.Order(order)
}
return q
}
func main() {
db, err := gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", Dbuser, Dbpwd, Dbname))
if err != nil {
panic("failed to connect database")
}
defer db.Close()
// Migrate the schema
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "L1213", Price: 1000})
// Find, Builder Pattern
Find(db, "L1213", 1000, "code DESC")
}