在updatesgorm 上不会将布尔类型更新为false. 默认情况下它会更新为true,但是当我尝试更新为false不更改时。我也没有看到任何错误。可能是什么问题?
type Attendee struct {
ID uint `gorm:"primary_key" gorm:"AUTO_INCREMENT" json:"id,omitempty" mapstructure:"id" csv:"ID"`
Email string `json:"email,omitempty" mapstructure:"email" csv:"Email,required"`
ShowDirectory bool `json:"show_directory,omitempty" gorm:"default:true" mapstructure:"show_directory" csv:"-"`
}
var attendee Attendee
// JSON.unmarshal lines here for the &attendee
if err := service.DB.Model(&attendee).Updates(Attendee{
Email: attendee.Email,
ShowDirectory: false
}).Error; err != nil {
return Attendee{}, err
}
Run Code Online (Sandbox Code Playgroud)
替代解决方案:
这有效,但我正在更新多个属性。所以,我不能用这个。
att := Attendee{ID: 1}
service.DB.Model(&att).Update("ShowDirectory", false)
Run Code Online (Sandbox Code Playgroud)
pra*_*mod 18
另一种方便的方法是将该字段设置为指针。
\n注意所有具有零值的字段,如 0、\'\'、false 或其他零值,都不会\xe2\x80\x99 保存到数据库中,但将使用其默认值。如果您想避免这种情况,请考虑使用指针类型或扫描仪/估价器链接
\n在您的情况下,模型将如下所示:
\ntype Attendee struct {\n ID uint `gorm:"primary_key" gorm:"AUTO_INCREMENT" json:"id,omitempty" mapstructure:"id" csv:"ID"`\n Email string `json:"email,omitempty" mapstructure:"email" csv:"Email,required"`\n \n ShowDirectory *bool `json:"show_directory,omitempty" gorm:"default:true" mapstructure:"show_directory" csv:"-"`\n}\nRun Code Online (Sandbox Code Playgroud)\n
7ur*_*m3n 14
正如@mkopriva 提到的,由 GORM文档
Run Code Online (Sandbox Code Playgroud)// Update attributes with `struct`, will only update non-zero fields db.Model(&user).Updates(User{Name: "hello", Age: 18, Active: false}) // UPDATE users SET name='hello', age=18, updated_at = '2013-11-17 > 21:34:10' WHERE id = 111; // Update attributes with `map` db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false}) // UPDATE users SET name='hello', age=18, actived=false, updated_at='2013-11-17 21:34:10' WHERE id=111;注意使用 struct 更新时,GORM 只会更新非零字段,您可能希望
map用于更新属性或用于Select指定要更新的字段
解决了:
if err := service.DB.Model(&attendee).Updates(map[string]interface{}{
"Email": attendee.Email,
"ShowDirectory": false
}).Error; err != nil {
return Attendee{}, err
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8633 次 |
| 最近记录: |