Gorm在使用另一个结构体进行封装时,无法正常工作的问题

huangapple go评论94阅读模式
英文:

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}]"

英文:

User can be deleted by another user. In that case,

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

DeletedBy will be null when we create a new user. So I used sql.NullInt64 instead of int64.
But I cannot convert to JSON.

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

For that, I tried https://gist.github.com/smagch/bc34f861df65c8ea2e90
But Gorm send query condition value as "[{2, true}]"

答案1

得分: 2

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

type NullInt64 sql.NullInt64

你的新类型 NullInt64sql.NullInt64 有相同的结构和内存布局,但是它没有原类型的方法,也就是 ScanValue 方法,这些方法是使其按照你的期望工作所必需的。

相反,你可以嵌入 sql.NullInt64,然后就可以使用了。

type NullInt64 struct {
    sql.NullInt64
}
英文:

In Go when you declare a type as an alias of another type, the new type does not get to keep the other type's methods. So here:

type NullInt64 sql.NullInt64

your new NullInt64 type has the same structure and memory layout as sql.NullInt64 but it does not have its methods, namely the Scan and Value methods required for it to work the way you want.

Instead what you can do is to embed the sql.NullInt64 and you should be good to go.

type NullInt64 struct {
    sql.NullInt64
}

huangapple
  • 本文由 发表于 2017年4月30日 07:09:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/43701322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定