根据戈姆(氏)
更新支持使用struct或mapstringinterface接口{}更新,当使用struct更新时,默认情况下它只更新非零字段。
我的数据库中已经有一个ID为Service,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,它将用空值覆盖我的DB中的值。使用time.Time,它尝试用未初始化的时间值覆盖DB中的值,并引发错误:Error 1292: Incorrect datetime value: '0000-00-00' for column 'created_at' at row 1
发布于 2020-09-11 18:56:41
结构中的time.Time字段类型的零值或默认值是time.Time{}。使用Updates时,要么不要填充CreatedAt字段,要么给它分配time.Time{}值。
在下面的示例中,在这两种情况下都会输出CreatedAt字段的默认值或零值。
package main
import (
"fmt"
"time"
)
type T struct {
CreatedAt time.Time
C int
S string
}
func main() {
fmt.Println(T{C: 1, S: "one"})
fmt.Println(T{C: 2, S: "two", CreatedAt: time.Time{}})
}
// {0001-01-01 00:00:00 +0000 UTC 1 one}
// {0001-01-01 00:00:00 +0000 UTC 2 two} 编辑:,我也不知道如果CreatedAt字段是time.Time类型,而不是*time.Time类型,甚至CreatedAt: nil,也是如何编译的。
由于您已经将Service结构和CreatedAt字段类型更新为*time.Time,下面的内容应该可以工作:
tx.Model(&service).Updates(Service{Name: service.Name}) // add all fields that you want to be updated.
// resulting query
// UPDATE services SET name = 'new service name' WHERE id = 'abc123';一个正式的GORM例子是这里
此外,您可以省略created_at字段,如下所示:
tx.Model(&service).Omit("created_at").Updates(service)发布于 2022-01-05 16:42:49
默认情况下,gorm不会更新默认值(零)或零值。如果您想要控制它,请使用如下所述的东西。您可以使用sql包提供的可空类型,也可以创建自己的类型。
type Model struct {
Amount *sql.NullFloat64
}
// amount will not be updated
gorm.Updates(Model{Amount: nil})
// amount will be updated as a null
gorm.Updates(Model{Amount: &sql.NullFloat64{}})
// amount will be updated as a 10.50
gorm.Updates(Model{Amount: &sql.NullFloat64{Float64: 10.50, Valid: true}})发布于 2020-11-03 10:11:50
使用map https://gorm.io/docs/update.html#Updates-multiple-columns
tx.Model(&service).Updates(map[string]interface{}{"ID": "abc123", "Name": "new service name", "CreatedAt": nil})https://stackoverflow.com/questions/63852322
复制相似问题