如何告诉gorm保存丢失的时间,时间字段为NULL而不是'0000-00- 00'?

8wtpewkr  于 2023-11-14  发布在  Go
关注(0)|答案(3)|浏览(293)

我为用户提供了这个自定义类型:

  1. type User struct {
  2. UserID uint64 `gorm:"primaryKey"`
  3. CreatedAt time.Time
  4. UpdatedAt time.Time
  5. LastLogin time.Time
  6. }

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

  1. return User{
  2. UserID: userID,
  3. AccountID: accountID,
  4. UserType: userType,
  5. Status: status,
  6. UserInfo: &userInfo,
  7. CreatedAt: now,
  8. UpdatedAt: now,
  9. }


因为LastLogin在MySQL中是一个可以为空的timestamp列,所以我没有在这里初始化它的值。
现在,gorm将在SQL语句中将未设置的值解析为'0000-00-00 00:00:00.000000',并导致以下错误。

  1. 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中将零Time字段作为NULL传递?

pw9qyyiw

pw9qyyiw1#

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

  1. type User struct {
  2. ID uint64 `gorm:"primaryKey"`
  3. CreatedAt time.Time
  4. LastLogin *time.Time
  5. }

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

  1. type User struct {
  2. ID uint64 `gorm:"primaryKey"`
  3. CreatedAt time.Time
  4. LastLogin sql.NullTime
  5. }


现在,当你在数据库中创建这个对象,并且没有设置LastLogin时,它将在数据库中保存为NULL。
https://gorm.io/docs/models.html
值得注意的是,如果使用sql.NullTime,在结构中您将看到一个默认的时间戳,而不是一个nil值

展开查看全部
ev7lccsx

ev7lccsx2#

像这样使用

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

字符串
它有助于使CompletedAt字段为空的时间戳类型

gcxthw6b

gcxthw6b3#

您可以在gorm标记中使用DEFAULT NULL,如下所示:

  1. type User struct {
  2. UserID uint64 `gorm:"primaryKey"`
  3. CreatedAt time.Time
  4. UpdatedAt time.Time
  5. LastLogin time.Time `gorm:"type:TIMESTAMP;null;default:null"`
  6. }

字符串
在这种情况下,gorm不会为LastLogin插入0000-00-00 00:00:00的零值。

相关问题