Gorm: 是否支持MySQL 5.7以上的 json type column的使用

Created on 2 May 2018  ·  11Comments  ·  Source: go-gorm/gorm

是否支持MySQL 5.7以上的 json type column的使用,找了下没有找到相关文档内容

Most helpful comment

type Demo struct {
  id string 
  obj  DemoObj  `sql:"TYPE:json"`
}

struct DemoObj struct {
   c1 string
   c2 int
   c3 bool
}

func (c DemoObj) Value() (driver.Value, error) {
  b, err := json.Marshal(c)
  return string(b), err
}

func (c *DemoObj) Scan(input interface{}) error {
  return json.Unmarshal(input.([]byte), c)
}

All 11 comments

type Demo struct {
  id string 
  obj  DemoObj  `sql:"TYPE:json"`
}

struct DemoObj struct {
   c1 string
   c2 int
   c3 bool
}

func (c DemoObj) Value() (driver.Value, error) {
  b, err := json.Marshal(c)
  return string(b), err
}

func (c *DemoObj) Scan(input interface{}) error {
  return json.Unmarshal(input.([]byte), c)
}

@lvzhihao thank you, I will try

亲测,可以!
但是,如果Demo中字段obj是数组DemoObj时就不行了

亲测,可以!
但是,如果Demo中字段obj是数组DemoObj时就不行了

应该加上数组的支持。

+1

+1

[] struct中的切片结构在db.Create()时不能被识别

type Book struct {
//....
FileUrlJson             []FileJson   `json:"file_url_json";gorm:"column:file_url_json;type:json"`
}

type FileJson struct {
    Url  string
    Name string
}

book := Book{
        FileUrlJson:             []FileJson{{Url: "aaa", Name: "bbb"}},
    }
    result := db.Debug().Create(&book)
    util.Log.Debug(result.GetErrors())   //  nothing 

显示的INSERT SQL里没有file_url_json的操作,也没有任何报错。

QAQ 如果FileUrlJson不是一个切片[]FileJson ,那就可以。

一个可行的方案是将数组需求,转嫁为模型Struct里指定的属性中

最后调整了一下方案,这个方案可以实现多个json存入一个字段的需求:

type Book struct {
FileUrlJson             FileJson     `json:"file_url_json";gorm:"column:file_url_json;type:json"`
}

type FileJson struct {
    //Url  string
    //Name string
    v []string #如果有需要,将Url和Name的需求扩展到v里,比如v []map[string]string
}

func (f FileJson) Value() (driver.Value, error) {
    b, err := json.Marshal(f.v)
    return string(b), err
}

func (f FileJson) Scan(input interface{}) error {
    return json.Unmarshal(input.([]byte), f.v)
}

book := Book{
        FileUrlJson: FileJson{v: []string{"file_address1", "file_address2"}},
    }
    result := db.Debug().Create(&book)

关键就在FileJson这个struct里存储了一个切片的v []string,插入的数据终于可以是数组json了。

其实像 xorm 那样,指定 json tag, 自动编码解码比较方便

nice

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Ganitzsh picture Ganitzsh  ·  3Comments

rfyiamcool picture rfyiamcool  ·  3Comments

fieryorc picture fieryorc  ·  3Comments

izouxv picture izouxv  ·  3Comments

sredxny picture sredxny  ·  3Comments