Gorm: 枚举类型问题

创建于 2014-11-26  ·  3评论  ·  资料来源: go-gorm/gorm

我有以下几点:

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() 加载这个结构,我会得到类似的错误

最有用的评论

我遇到过同样的问题。 @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 :

所有3条评论

经过一些调试,这个错误似乎是从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 文档中。

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

RadhikaBhat picture RadhikaBhat  ·  3评论

youtwo123 picture youtwo123  ·  3评论

easonlin404 picture easonlin404  ·  3评论

sredxny picture sredxny  ·  3评论

corvinusy picture corvinusy  ·  3评论