doumi5223 2018-09-09 11:22 采纳率: 100%
浏览 1782
已采纳

报错: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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失