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 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)