如何告诉 gorm 将丢失的 time.Time 字段保存为 NULL 而不是 '0000-00-00'?

How to tell gorm to save missing time.Time fields as NULL and not '0000-00-00'?

我有这样的用户自定义类型:

type User struct {
    UserID    uint64 `gorm:"primaryKey"`
    CreatedAt time.Time
    UpdatedAt time.Time
    LastLogin time.Time
}

当传递给 gorm 的 db.Create() 方法时,用户初始化如下:

return User{
    UserID:    userID,
    AccountID: accountID,
    UserType:  userType,
    Status:    status,
    UserInfo:  &userInfo,
    CreatedAt: now,
    UpdatedAt: now,
}

因为 LastLogin 是 MySQL 中可空的 timestamp 列,我没有在这里初始化它的值。

现在gorm会在SQL语句中将未设置的值解析为'0000-00-00 00:00:00.000000',并导致如下错误。

Error 2021-01-29 15:36:13,388 v1(7) error_logger.go:14 192.168.10.100 - - default - 0 Error 1292: Incorrect datetime value: '0000-00-00' for column 'last_login' at row 1

虽然我理解 MySQL 如何在不更改某些模式的情况下不允许零时间戳值,但我可以轻松地将 time.Time 字段初始化为一些遥远的日期,例如2038 左右。我如何告诉 gorm 在 SQML​​ 中将零时间字段作为 NULL 传递?

所以你在这里有几个选择。您可以使 LastLogin 成为一个指针,这意味着它可以是一个 nil 值:

type User struct {
    ID        uint64 `gorm:"primaryKey"`
    CreatedAt time.Time
    LastLogin *time.Time
}

或者像@aureliar 提到的那样,您可以使用 sql.NullTime 类型

type User struct {
    ID        uint64 `gorm:"primaryKey"`
    CreatedAt time.Time
    LastLogin sql.NullTime
}

现在,当您在数据库中创建该对象并且不设置 LastLogin 时,它将在数据库中保存为 NULL。

https://gorm.io/docs/models.html

值得注意的是,如果你使用sql.NullTime,在结构中你会看到一个默认的时间戳而不是一个空值

这样使用

type Test struct {
    ID uint64 `gorm:"primary_key" json:"id"`
    CompletedAt sql.NullTime `gorm:"type:TIMESTAMP NULL"`
}

它有助于使 CompletedAt 字段可为空时间戳类型