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

报错: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 学习Python如何找兼职
  • ¥15 python结合Matlab仿真忆阻器
  • ¥35 有人会注册whatsaop协议号吗?
  • ¥15 lead dbs 无法导入影像数据
  • ¥15 多目标MPA算法优化编程实现
  • ¥15 反激PWM控制芯片调研
  • ¥15 Python for loop减少运行时间
  • ¥15 fluent模拟物质浓度udf
  • ¥15 Collection contains no element matching the predicate
  • ¥20 冻品电商平台的搜索是怎么实现的