gorm自定义类型
package dbjson import ( "database/sql/driver" "encoding/json" "errors" "fmt" ) // JSONArray 自定义类型:存 []map[string]interface{} 到 text/jsonb 字段 type JSONArray []map[string]interface{} // 存入数据库:slice → JSON 字符串 func (a JSONArray) Value() (driver.Value, error) { if a == nil { return nil, nil } return json.Marshal(a) } // 从数据库读取:JSON 字符串 → slice func (a *JSONArray) Scan(value interface{}) error { if value == nil { *a = nil return nil } switch v := value.(type) { case []byte: return json.Unmarshal(v, a) case string: return json.Unmarshal([]byte(v), a) default: return errors.New(fmt.Sprintf("无法将 %T 扫描到 JSONArray", value)) } }package dbjson import ( "database/sql/driver" "encoding/json" "errors" "fmt" ) type JSONArrayStr []string // 存入数据库:slice → JSON 字符串 func (a JSONArrayStr) Value() (driver.Value, error) { if a == nil { return nil, nil } return json.Marshal(a) } // 从数据库读取:JSON 字符串 → slice func (a *JSONArrayStr) Scan(value interface{}) error { if value == nil { *a = nil return nil } switch v := value.(type) { case []byte: return json.Unmarshal(v, a) case string: return json.Unmarshal([]byte(v), a) default: return errors.New(fmt.Sprintf("无法将 %T 扫描到 JSONArray", value)) } }type WordIndex struct { // 当前组模式mode1-6 CurrentMode string `json:"currentMode" gorm:"column:current_mode;type:character varying(10)"` // 当前轮次1,2,3 CurrentRound int32 `json:"currentRound" gorm:"column:current_round;type:integer"` // 当前单词索引1,2,3 WordIndex int32 `json:"wordIndex" gorm:"column:word_index;type:integer"` // 10 20 30 31-36 NewBulge int `json:"newBulge"` // groupType = word 0 时,当前页码 fsrs PageCurrent int `json:"pageCurrent" gorm:"column:page_current;type:int"` //复习上次训练单词 Filters dbjson.JSONArrayInt64 `json:"filters" gorm:"column:filters;type:text"` //训练上次的筛查单词,与modes配套 ,>0 words 为单词列表, =0 fsrs 单词列表 LastWords dbjson.JSONArrayInt64 `json:"lastWords" gorm:"column:last_words;type:text"` // 所有训练的单词列表 AllWords dbjson.JSONArrayInt64 `json:"allWords" gorm:"column:all_words;type:text"` //本组训练单词,与modes配套 ,>0 words 为单词列表, =0 fsrs 单词列表 Words dbjson.JSONArrayInt64 `json:"words" gorm:"column:words;type:text"` //为下一组准备的数据 NextWords dbjson.JSONArrayInt64 `json:"nextWords" gorm:"column:next_words;type:text"` }这篇文章摘要介绍了一个处理数据库JSON数据的Go语言实现方案。主要包含两个自定义类型:JSONArray(处理[]map[string]interface{}类型)和JSONArrayStr(处理字符串切片),它们实现了driver.Valuer和sql.Scanner接口,用于JSON数据与数据库之间的序列化和反序列化。此外还定义了一个WordIndex结构体,展示了这些自定义类型在ORM中的实际应用场景,包括存储单词训练相关的各种索引数据(如当前模式、轮次、单词列表等)。
