英文:
gorm datetime null fetch wrong value
问题
我正在使用gorm获取一些数据,但有一个行为不符合我的预期。
实体(由gen生成):
type Test struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
Time time.Time `gorm:"column:time" json:"time"`
}
数据:
| ID | time |
| -------- | --------------------- |
| 1 | null |
| 2 | 2022-11-16 16:31:31 |
| 3 | null |
| 4 | null |
代码:
var tests []entity.Test
orm.Find(&tests)
fmt.Printf("%+v\n", tests)
期望结果:
[
{
"id": 1,
"time": "0001-01-01T00:00:00Z"
},
{
"id": 2,
"time": "2022-11-16T16:31:31+08:00"
},
{
"id": 3,
"time": "0001-01-01T00:00:00Z"
},
{
"id": 4,
"time": "0001-01-01T00:00:00Z"
}
]
实际结果:
[
{
"id": 1,
"time": "0001-01-01T00:00:00Z"
},
{
"id": 2,
"time": "2022-11-16T16:31:31+08:00"
},
{
"id": 3,
"time": "2022-11-16T16:31:31+08:00"
},
{
"id": 4,
"time": "2022-11-16T16:31:31+08:00"
}
]
当Time
字段为null
时,其值被前一个值覆盖了。
我注意到,当将Time
字段设置为字符串时,我可以得到正确的值,像这样:
type Test struct {
ID int32
Time string
T int32
}
英文:
I'm using gorm to get some data,but there is a behavior works not what I think.
entity(generate by gen):
type Test struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
Time time.Time `gorm:"column:time" json:"time"`
}
data:
| ID | time |
| -------- | --------------------- |
| 1 | null |
| 2 | 2022-11-16 16:31:31 |
| 3 | null |
| 4 | null |
code:
var tests []entity.Test
orm.Find(&tests)
fmt.Printf("%+v\n", tests)
expecting:
[
{
"id": 1,
"time": "0001-01-01T00:00:00Z"
},
{
"id": 2,
"time": "2022-11-16T16:31:31+08:00"
},
{
"id": 3,
"time": "0001-01-01T00:00:00Z"
},
{
"id": 4,
"time": "0001-01-01T00:00:00Z"
}
],
what I get:
[
{
"id": 1,
"time": "0001-01-01T00:00:00Z"
},
{
"id": 2,
"time": "2022-11-16T16:31:31+08:00"
},
{
"id": 3,
"time": "2022-11-16T16:31:31+08:00"
},
{
"id": 4,
"time": "2022-11-16T16:31:31+08:00"
}
]
When the TIME feild is null the value get coverd by previous one.
And I notice that when set the Time feild to string I can get the right value.like this:
type Test struct {
ID int32
Time string
T int32
}
答案1
得分: 1
当TIME字段为空时,该值会被前一个值覆盖。
请在数据库中检查一下,确保你的程序读取的是相同的数据;对于空值,这种情况不应该发生。
建议:对于这种情况,请使用sql.NullTime
,这样空值在数据库中仍然保持为空,当保存实体时,time.Time
会将这些列默认为零时间。
英文:
> When the TIME feild is null the value get coverd by previous one.
Please check this in the database that it is the same data that your program is reading; This should not happen for null values.
Suggestion: Please use sql.NullTime
for such use cases, so that null values remain null in the database, time.Time
will default to zero time for such columns when the entity is saved.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论