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

报错: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 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图