我使用的是最新版本的xorm,并希望创建一个简单的go结构,如下所示:
types myStruct struct {
isDeleted bool `xorm:"'isDeleted' tinyint(3)"`
}我知道go中的bool类型为true和false,但我需要将其映射到mySql数据库,其中值为tinyint(3),1映射为true,0映射为false。在上面的例子中,无论我的post请求看起来像什么,isDeleted总是计算为0。提前感谢您对此问题的任何建议。这个https://github.com/go-xorm/xorm/issues/673可能提供一些上下文。
发布于 2018-11-21 18:09:02
我不知道xorm能做些什么,但是您可以为它创建一个类型并实现Valuer和Scanner接口。下面是一个示例,我为bit(1)的bool使用了一个拉请求。
https://github.com/jmoiron/sqlx/blob/master/types/types.go#L152
对于整数,只需返回int,而不是包含int的[]byte。就像这样:
type IntBool bool
// Value implements the driver.Valuer interface,
// and turns the IntBool into an integer for MySQL storage.
func (i IntBool) Value() (driver.Value, error) {
if i {
return 1, nil
}
return 0, nil
}
// Scan implements the sql.Scanner interface,
// and turns the int incoming from MySQL into an IntBool
func (i *IntBool) Scan(src interface{}) error {
v, ok := src.(int)
if !ok {
return errors.New("bad int type assertion")
}
*i = v == 1
return nil
}然后,您的结构将只使用新类型。
type myStruct struct {
isDeleted IntBool `xorm:"'isDeleted' tinyint(3)"`
}但是,再次声明这个布尔值为tinyint有什么特别的原因吗?MySQL 有一个布尔类型的,一切都会正常工作的。
https://stackoverflow.com/questions/53417403
复制相似问题