Tengo lo siguiente:
type BufferType string
const (
Console BufferType = "console"
Channel BufferType = "channel"
Conversation BufferType = "conversation"
)
type Buffer struct {
Bid int64 `gorm:"primary_key:yes"`
Type BufferType `sql:"not null;type:ENUM('console', 'channel', 'conversation')"`
Name string `sql:"size:255;not null"`
}
Cuando intento db.Save (búfer), aparece el siguiente error:
sql: converting Exec argument #1's type: unsupported type BufferType, a string)
¿Sería posible resolver que BufferType es realmente solo una cadena y guardar? Recibo errores similares si intento cargar esta estructura con db.Find ()
Después de un poco más de depuración, este error parece provenir de la base de datos golang / código sql, y encontré una solución aquí . Solo necesitaba agregar:
func (u *BufferType) Scan(value interface{}) error { *u = BufferType(value.(string)); return nil }
func (u BufferType) Value() (driver.Value, error) { return string(u), nil }
Es un poco torpe, pero ayuda a la base de datos a saber cómo mapear correctamente. También podría agregar la comprobación de errores aquí si lo necesitara.
Tuve el mismo problema. La solución de @bramp todavía me dio un error. Lo siguiente funcionó para mí:
func (u *BufferType) Scan(value interface{}) error { *u = BufferType(value.([]byte)); return nil }
func (u BufferType) Value() (driver.Value, error) { return string(u), nil }
La diferencia es usar []byte
lugar de string
. Este hilo de stackoverflow me ayudó: http://stackoverflow.com/a/20582504/2418739
+1 gran solución. Ojalá esto estuviera en los documentos GORM.
Comentario más útil
Tuve el mismo problema. La solución de @bramp todavía me dio un error. Lo siguiente funcionó para mí:
La diferencia es usar
[]byte
lugar destring
. Este hilo de stackoverflow me ayudó: http://stackoverflow.com/a/20582504/2418739