dowaw80220 2019-06-18 16:27
浏览 941
已采纳

GORM不会将布尔字段更新为false

On updates gorm doesnt update boolean type to false. By default it updates to true, but when i try to update to false not changes. I dont see any errors also. What can be the issue ?

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
}

Alternate Solution:

This works, but I am updating multiple attributies. So, I cant use this.

    att := Attendee{ID: 1}
    service.DB.Model(&att).Update("ShowDirectory", false)
  • 写回答

2条回答 默认 最新

  • dsiy62758 2019-06-18 16:48
    关注

    As @mkopriva mentioned, by GORM Documentation

    // WARNING when update with struct, GORM will only update those fields that with non blank value

    // For below Update, nothing will be updated as "", 0, false are blank values of their types

    db.Model(&user).Updates(User{Name: "", Age: 0, Actived: false})

    Solved:

    if err := service.DB.Model(&attendee).Updates(map[string]interface{}{
        "Email":          attendee.Email,
        "ShowDirectory": false
    }).Error; err != nil {
        return Attendee{}, err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan