当我们用另一个结构包装时,Gorm golang sql.NullInt64 不起作用

Gorm golang sql.NullInt64 not working when we wrapper with another struct

用户可以被其他用户删除。那样的话,

type User struct {
    gorm.Model
    Email string `gorm:"type:varchar(100)"`
    DeletedBy     sql.NullInt64
}

创建新用户时DeletedBy为空。所以我使用 sql.NullInt64 而不是 int64。 但我无法转换为 JSON。

{ "Email": "xxxxx", "DeletedBy": {"Int64":2,"Valid":true} }

为此,我尝试了 https://gist.github.com/smagch/bc34f861df65c8ea2e90 但是 Gorm 将查询条件值发送为 "[{2, true}]"

在 Go 中,当您将类型声明为另一种类型的 别名 时,新类型 不会保留 另一种类型的方法。所以在这里:

type NullInt64 sql.NullInt64

您的新 NullInt64 类型具有与 sql.NullInt64 相同的结构和内存布局 但是 它没有其方法,即 Scan and Value 所需的方法使其按照您想要的方式工作。

您可以做的是嵌入 sql.NullInt64,这样您就可以开始了。

type NullInt64 struct {
    sql.NullInt64
}