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

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

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

最佳答案

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

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

对于整数,您只需返回int而不是包含[]byteint即可。像这样:

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)"`
}

但是,再次声明您将此 bool(boolean) 值声明为tinyint是否有任何特定原因? MySQL 具有boolean类型的,一切正常。

07-27 14:04