我为用户提供了以下自定义类型:
type User struct { UserID uint64 `gorm:"primaryKey"` CreatedAt time.Time UpdatedAt time.Time LastLogin time.Time }
当传递给gorm的 db.Create() 方法时,用户初始化如下:
db.Create()
return User{ UserID: userID, AccountID: accountID, UserType: userType, Status: status, UserInfo: &userInfo, CreatedAt: now, UpdatedAt: now, }
因为 LastLogin 在MySQL中是一个可以为空的 timestamp 列,所以我没有在这里初始化它的值。
LastLogin
timestamp
现在gorm将在SQL语句中将未设置的值解析为 '0000-00-00 00:00:00.000000' ,并导致以下错误。
'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将零时间字段作为NULL传递到SQML中?
上云精选
2核2G云服务器 每月9.33元起,还有更多云产品低至0.02元
所以你有几个选择。您可以将 LastLogin 设为指针,这意味着它可以是一个 nil 值:
nil
type User struct { ID uint64 `gorm:"primaryKey"` CreatedAt time.Time LastLogin *time.Time }
或者像@aureliar提到的那样,你可以使用sql.NullTime类型
type User struct { ID uint64 `gorm:"primaryKey"`