Skip to content

GORM Update

会忽略零值字段(默认值)

go
type User struct {
  Name string
  Age  int
}
db.Model(&user).Updates(User{Name: "Tom", Age: 0})

这条语句中,Age: 0 会被忽略,因为 GORM 默认只更新非零值字段。

Solutions

Model.Update(column, value)

go
db.Model(&user).Update("age", 0) // 会把 age 更新为 0

使用 Map

go
db.Model(&user).Updates(map[string]interface{}{"age": 0})

使用 Select()

go
db.Model(&user).Select("age").Updates(User{Age: 0})

使用 Save

go
db.Save(&User{Name: "", Age: 0})

WARNING

会更新所有字段