我有以下几点:
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"`
}
当我尝试 db.Save(buffer) 时,出现以下错误:
sql: converting Exec argument #1's type: unsupported type BufferType, a string)
是否有可能解决 BufferType 实际上只是一个字符串并保存? 如果我尝试使用 db.Find() 加载这个结构,我会得到类似的错误
经过一些调试,这个错误似乎是从golang database/sql代码中出来的,我在这里找到了解决方案。 我只需要添加:
func (u *BufferType) Scan(value interface{}) error { *u = BufferType(value.(string)); return nil }
func (u BufferType) Value() (driver.Value, error) { return string(u), nil }
它有点笨重,但它有助于数据库知道如何正确映射。 如果需要,我还可以在此处添加错误检查。
我遇到过同样的问题。 @bramp的解决方案还是报错了。 以下对我有用:
func (u *BufferType) Scan(value interface{}) error { *u = BufferType(value.([]byte)); return nil }
func (u BufferType) Value() (driver.Value, error) { return string(u), nil }
不同之处在于使用[]byte
而不是string
。 这个stackoverflow线程帮助了我: http :
+1 很棒的解决方案。 我希望这是在 GORM 文档中。
最有用的评论
我遇到过同样的问题。 @bramp的解决方案还是报错了。 以下对我有用:
不同之处在于使用
[]byte
而不是string
。 这个stackoverflow线程帮助了我: http :