1

我正在使用最新版本的 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可能会提供一些上下文。

4

1 回答 1

4

我不确定xorm可以做什么/如果可以,但您可以创建一个类型并为其实现ValuerScanner接口。这是一个示例,我为使用 abit(1)进行了拉取请求bool

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

对于整数,您只需返回包含的int而不是 a 。像这样:[]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)"`
}

但是,再一次,您将这个布尔值声明为 a 有什么特别的原因tinyint吗?MySQL一个布尔类型,一切都可以正常工作。

于 2018-11-21T18:09:02.070 回答