GORM - 小记

# 自定义数据结构

 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
type StringMap struct {
	Src   map[string]string
	Valid bool
}

func NewEmptyStringMap() *StringMap {
	return &StringMap{
		Src:   make(map[string]string),
		Valid: true,
	}
}

func NewStringMap(src map[string]string) *StringMap {
	return &StringMap{
		Src:   src,
		Valid: true,
	}
}

func (ls *StringMap) Scan(value interface{}) error {
	if value == nil {
		ls.Src, ls.Valid = make(map[string]string), false
		return nil
	}
	t := make(map[string]string)
	if e := json.Unmarshal(value.([]byte), &t); e != nil {
		return e
	}
	ls.Valid = true
	ls.Src = t
	return nil
}

func (ls *StringMap) Value() (driver.Value, error) {
	if ls == nil {
		return nil, nil
	}
	if !ls.Valid {
		return nil, nil
	}

	b, e := json.Marshal(ls.Src)
	return b, e
}
1
2
3
4
5
6
7
8
type User struct {
    Info *StringMap `gorm:"type:json"`
}

u := &User{
     Info: NewEmptyStringMap(), // 这样会初始化map,即使不设置任何值,保存后在db中的值为`{}`
}
u.Info.Src["nihao"] = "123"

# where 查询 in 条件参数类型必须是显式的数组类型

# 错误写法

JSONArray 无法被正常解析

1
2
3
4
5
6
7
type JSONArray []interface{}

var relation JSONArray

db.DB().Table("account").Debug().
			Where("isDelete = 'no' AND id in (?) AND creatorId = ?", relation, createID).
			Find(&accounts)

SQL:

1
SELECT * FROM `account` WHERE (isDelete = 'no' AND id in ('[2]') AND creatorId = '1’)

# 正确写法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
type JSONArray []interface{}

var relation JSONArray

var _relation []interface{}
_relation = relation

db.DB().Table("account").Debug().
			Where("isDelete = 'no' AND id in (?) AND creatorId = ?", _relation, createID).
			Find(&accounts)

SQL:

1
SELECT * FROM `account` WHERE (isDelete = 'no' AND id in ('2') AND creatorId = '1’)
Licensed under CC BY-NC-SA 4.0