想要在数据库中存储 []string 类型的数据
gorm 存储数组格式的数据,其实原理和存储Json格式数据是一样的
1.先定义一个类型
type StringArr []string
// 实现 driver.Valuer 接口
func (s StringArr) Value() (driver.Value, error) {
if s == nil {
return "[]", nil
}
return json.Marshal(s)
}
// 实现 sql.Scanner 接口
func (s *StringArr) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return errors.New(fmt.Sprint("Failed to scan Array value:", value))
}
if len(bytes) > 0 {
return json.Unmarshal(bytes, s)
}
*s = make([]string, 0)
return nil
}
2.定义数据库结构
type Gift struct {
BaseModel
Title string `json:"title"`
Images StringArr `json:"images"`
}
3.存储
gift_ := models.Gift{
Title: "围巾",
Images: ["pic_path.jpg","pic_path.jpg"],
}
db.Create(&gift_)