Gorm uses update to update database (postgresql) Boolean values

problem description:

the problem we encountered this morning has been going on all morning, but we still haven"t found out what the problem is. Come to ask
purpose: use gorm to modify the Boolean value of a field in the database table

Code first:

func ChangeActive(id int) (*models.Comment, error) {
    var (
        model     *models.Comment
        pre_model models.PreComment
        err       error
    )

    //
    err = common.DB.Where("id = ?", id).First(&model).Error
    if err != nil {
        return nil, err
    }
    //
    model.IsActive = !model.IsActive
    //
    common.DB.Model(&model).Updates(&model)

    if !model.IsActive {
        pre_model.Create(common.DB)
    }

    return model, err
}
this function receives a ID , queries out the data corresponding to ID in the database, and modifies the active field of this data to reverse it. Finally, update the database.
The Bug: Boolean value encountered by

cannot be updated all the time.

troubleshooting process: at first I thought there was something wrong with the code statement, so I used goland"s Debug mode and found that there was nothing wrong with the code.

then I verify that modifies another field (model.CompanyID = 3) before updating the data table to see if the modification is successful. The result is that the modification is successful, but the Boolean value remains the same.

Mar.25,2021

    If
  • is zero, then the Updates method does not update this field, while the zero value of the Boolean value is false .
  • method 1: change the attribute from bool to * bool .
  • method 2: use other update methods.
Menu