doumi5223
2018-09-09 11:22
采纳率: 100%
浏览 1.2k

报错:Go-gorm mysql“不受支持的类型[] string,字符串的一部分”

我尝试用 gorm 创建 mysql 事务,这是代码:

type Game struct {
    Images []string
}

game := Game{Images: []string{"1.png", "2.png"}}

db := Database()

tx := db.Begin()

if err := tx.Create(&game).Error; err != nil {
    tx.Rollback()
    return errors.New("Cannot add game")
}

tx.Commit()

但我收到报错如下:(sql: converting argument $1 type: unsupported type []string, a slice of string)我知道 mysql 不支持这种类型,但是我能用某种方式解决这个问题吗? 我想我可以把字体改成Json.rawmessage,但我认为这是错误的方式。

"github.com/jinzhu/gorm/dialects/mysql"
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • du16178 2018-09-09 17:19
    已采纳

    If you want a list of something in MySql, you have two options

    1. You could serialize the list yourself (into a comma-separated string, json, or another serialization format) and store it in a string or bytes column.
    2. You can use join to associate the two tables.

    gorm supports joins through something it calls associations. In this case, you have a has many association (http://doc.gorm.io/associations.html#has-many).

    An example of how you might do this is:

    type Game struct {
        gorm.Model
        GameImages   []GameImage
    }
    
    type GameImage struct {
        gorm.Model
        Name string
    }
    
    db.Model(&game).Related(&gameImages)
    
    点赞 打赏 评论
  • Tom Iron 2021-08-06 15:28

    这个问题我也遇到了,可以先转换成JSON格式,然后再通过自定义JSON类型使得gorm库可以支持,我写了一篇博客详细介绍了该过程,可以移步: golang-gorm库不支持[]string类型问题的解决方法 https://blog.csdn.net/weixin_43811340/article/details/119455488?spm=1001.2014.3001.5502

    点赞 打赏 评论

相关推荐 更多相似问题