为了账号安全,请及时绑定邮箱和手机立即绑定

GORM 逗号分隔值字段

GORM 逗号分隔值字段

Go
慕森王 2022-08-09 16:51:25
首先,我知道这是不好的做法,无论如何我都可以在客户端进行拆分,但我想知道如何在后端实现它。我有这个结构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}但是,如何在我的结构中将其实现为自定义类型,以便它自动拆分标签,并且最好在设置标签值时也加入[]字符串值?附言:上面的结构只是一个例子。
查看完整描述

1 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

根据注释和此链接,一个选项是创建自定义类型。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

}


查看完整回答
反对 回复 2022-08-09
  • 1 回答
  • 0 关注
  • 155 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信