我为用户提供了这种自定义类型:
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,在结构中您将看到默认时间戳而不是 nil 值
这样使用
type Test struct {
ID uint64 `gorm:"primary_key" json:"id"`
CompletedAt sql.NullTime `gorm:"type:TIMESTAMP NULL"`
}
它有助于使 CompletedAt 字段可为空时间戳类型
您可以在
DEFAULT NULL
标签中使用 gorm
,如下所示:
type User struct {
UserID uint64 `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
LastLogin time.Time `gorm:"type:TIMESTAMP;null;default:null"`
}
在这种情况下,
gorm
不会为0000-00-00 00:00:00
插入零值LastLogin
。