5

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"

1
  • 2
    You can store it in a string that contains JSON encoded data, and marshal/unmarshal it as you write/read from the DB. However, the reason why this type isn't supported is because MySQL isn't supposed to be used like that. You should have an image table with a game ID in it and a path string or something like that instead. Commented Sep 9, 2018 at 12:19

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use datatypes.JSON as your type

import "gorm.io/datatypes"

type Game struct {
     Images datatypes.JSON `json:"images"`
}

reference: https://github.com/go-gorm/datatypes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.