将bool转换为tinyint golang



我正在使用最新版本的xorm,并希望创建一个简单的go结构,如下所示:

types myStruct struct {
isDeleted bool `xorm:"'isDeleted' tinyint(3)"`
}

我知道go中的bool类型计算结果为true和false,但我需要将其映射到mySql数据库,其中的值为tinyint(3(,1映射为true,0映射为false。在上面的例子中,无论我的帖子请求是什么样子,isDeleted总是计算为0。提前感谢您对这个问题的任何建议。这https://github.com/go-xorm/xorm/issues/673可以提供一些上下文。

我不确定xorm能做些什么,但你可以创建一个类型并为它实现ValuerScanner接口。下面是一个例子,我为bool使用bit(1)做了一个pull请求。

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具有布尔类型,一切正常。

最新更新