【问题标题】:GORM comma separated values fieldGORM 逗号分隔值字段
【发布时间】:2021-02-13 19:27:26
【问题描述】:

首先我知道这是不好的做法,无论如何我都可以在客户端进行拆分,但我想知道如何在后端实现它。

我有这个结构

type Article struct{
    ArticleId   int    `gorm:"column:article_id;primaryKey" json:"article_id"`
    Title       string `gorm:"column:title" json:"title"`
    Content     string `gorm:"column:content" json:"content"`
    Tags        string `gorm:"column:tags" json:"tags"`
}

对于标签,我使用逗号分隔值,例如tech,woman,mit

我可以实现一个简单的函数来手动拆分字符串

func splitTags(values string) []string {
    array := strings.Split(values, ",")
    return array
}

但是如何在我的结构中将它实现为自定义类型,以便它自动拆分标签,并且最好在我设置标签值时加入 []string 值?

附:上面的结构只是一个例子。

【问题讨论】:

标签: go go-gorm


【解决方案1】:

对于每个 cmets 和这个 link,一种选择是创建自定义 Tags 类型。

type Tags []string

//Implement Scanner interface
func (t *Tags) Scan(value interface{}) error {
  val, ok := value.([]byte)
  if !ok {
    return errors.New(fmt.Sprint("wrong type", value))
  }
    
  *t = Tags(strings.Split(string(val), ","))
    
  return nil
}

//Implement Valuer interface
func (t Tags) Value() (driver.Value, error) {
  //this check is here if you don't want to save an empty string
  if len(t) == 0 {
    return nil, nil
  }

  return []byte(strings.Join(t, ",")), nil
}

【讨论】:

  • 使用Tags Tags gorm:"column:tags" json:"tags"`` 给出错误类型声明func (Tags) GormDataType() string { return "tag" } 和使用Tags []string gorm:"column:tags;type :tag" json:"tags"`` 给出关于将 uint8 转换为字符串并最终使用 Tags []uint8 gorm:"column:tags;type:tag" json:"tags"`` 的错误,但不会产生错误,但会产生标签的哈希值由于数据类型而合乎逻辑的值我做错了什么?
  • 也许它只需要在 ScanValue 方法内进行更改。像val, ok := value.([]byte)*t = Tags(strings.Split(string(val), ","))return []byte(strings.Join(t, ",")), nil 一样,保持type Tags []string 不变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-08
  • 2010-10-18
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多