【问题标题】:gorm datetime null fetch wrong valuegorm datetime null 获取错误值
【发布时间】:2022-11-24 18:55:48
【问题描述】:

我正在使用 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 时,该值将被前一个覆盖。

我注意到,当将时间字段设置为字符串时,我可以获得正确的值。像这样:

type Test struct {
    ID   int32
    Time string
    T    int32
}

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    当 TIME 字段为 null 时,该值将被前一个覆盖。

    请在数据库中检查它是否与您的程序正在读取的数据相同;这不应该发生在 null 值上。

    建议:对于此类用例,请使用sql.NullTime,以便空值在数据库中保持为空,time.Time将在保存实体时将此类列默认为零时间。

    【讨论】:

    • 谢谢,sql.NullTime 工作正常,就像string。但我想知道为什么time.Time 会这样。我正在阅读源代码,希望能得到一些线索。
    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 2022-12-17
    相关资源
    最近更新 更多