将bool转换为tinyint golang

时间:2018-11-21 17:16:03

标签: go go-xorm

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

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

我知道go中的​​布尔类型的值为true和false,但是我需要将其映射到mySql数据库,其中的值是tinyint(3),而1则映射为true,0则映射为false。在上面的示例中,无论我的帖子请求是什么样的,isDeleted始终评估为0。在此问题上的任何建议,请先感谢。该https://github.com/go-xorm/xorm/issues/673可以提供一些上下文。

1 个答案:

答案 0 :(得分:2)

我不确定xorm可以做什么,但是您可以创建一个类型并为其实现ValuerScanner接口。这是我为bit(1)使用bool的请求请求的例子。

https://github.com/jmoiron/sqlx/blob/master/types/types.go#L152

对于整数,您只需返回int而不是包含[]byte的{​​{1}}。像这样:

int

然后您的结构将只使用新类型

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)"` } 有什么特殊原因吗? MySQL 具有布尔类型,一切正常。

相关问题