小编Eri*_* L.的帖子

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

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

type User struct {
    UserID    uint64 `gorm:"primaryKey"`
    CreatedAt time.Time
    UpdatedAt time.Time
    LastLogin time.Time
}
Run Code Online (Sandbox Code Playgroud)

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

return User{
    UserID:    userID,
    AccountID: accountID,
    UserType:  userType,
    Status:    status,
    UserInfo:  &userInfo,
    CreatedAt: now,
    UpdatedAt: now,
}
Run Code Online (Sandbox Code Playgroud)

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

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

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
Run Code Online (Sandbox Code Playgroud)

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

mysql time timestamp go go-gorm

2
推荐指数
1
解决办法
978
查看次数

unsafe.SizeOf() 表示任何字符串都需要 16 个字节,但是如何呢?

只需运行fmt.Println(unsafe.Sizeof(""))prints 16。更改字符串的内容不会影响结果。

有人能解释一下这个数字(16)是怎么来的吗?

string go

1
推荐指数
1
解决办法
1186
查看次数

标签 统计

go ×2

go-gorm ×1

mysql ×1

string ×1

time ×1

timestamp ×1