我为用户提供了这种自定义类型:
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值
关于mysql - 如何告诉gorm保存丢失的时间。时间字段为NULL而不是 '0000-00-00'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65951219/