【发布时间】:2022-01-06 00:42:49
【问题描述】:
根据GORM's docs:
Updates 支持使用 struct 或 map[string]interface{} 进行更新,当 使用 struct 更新默认只会更新非零字段
我的数据库中已经有一个Service 的条目,ID 为abc123。我正在尝试获取如下所示的对象:
Service{
ID: "abc123",
Name: "new service name",
CreatedAt: nil,
}
并用它来更新我现有的记录。但是当我打电话时:
tx.Model(&service).Updates(service)
数据库中的CreatedAt 值被nil 覆盖。如何在不覆盖CreatedAt 值的情况下更新我的数据库记录?
更新:下面是我的 Service 结构
type Service struct {
ID string `gorm:"not null;type:char(32);primary_key;column:id"`
Name string `json:"name" gorm:"size:50;not null;"`
CreatedAt *time.Time
UpdatedAt time.Time
DeletedAt *time.Time `gorm:"index"`
}
我为 Service 结构尝试了两种不同的变体。另一种是CreatedAt 的类型为time.Time 而不是*time.Time。使用*time.Time,它将用空值覆盖我的数据库中的值。使用time.Time,它会尝试用未初始化的时间值覆盖数据库中的值并抛出错误:Error 1292: Incorrect datetime value: '0000-00-00' for column 'created_at' at row 1
【问题讨论】:
-
请提供您对
type Service struct {...}的定义 -
@bambula - 更新
-
time.Time字段的零值为time.Time{}。你试过用nil代替吗? -
如果
CreatedAt是time.Time那么CreatedAt: nil,将无法编译,您能否显示实际代码,它可能很重要。 -
@mkopriva - 你说得对,我更新了我的结构以反映我实际设置它的方式。