英文:
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
你的新类型 NullInt64
与 sql.NullInt64
有相同的结构和内存布局,但是它没有原类型的方法,也就是 Scan 和 Value 方法,这些方法是使其按照你的期望工作所必需的。
相反,你可以嵌入 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论