Go-gorm mysql "unsupported type []string, a slice of string"

Georgy picture Georgy · Sep 9, 2018 · Viewed 10.4k times · Source

I use gorm, and try to create transaction to mysql. I have a struct

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()

But I get error (sql: converting argument $1 type: unsupported type []string, a slice of string). I understand, that mysql unsupported this type, but can I someway resolve this problem? I guess I can change type to json.rawMessage, but I think it's a wrong way.

I use dialect "github.com/jinzhu/gorm/dialects/mysql"

Answer

dolan picture dolan · Sep 9, 2018

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)