0

I'm trying to update an existing record in PostgreSQL database. I have a column which accepts integers. I have tried doing the update using db query written in gorm. All the integers are getting updated except 0 (zero).

Can anyone help me fix this issue?

type RoleTypes struct {
    ID       int `gorm:"primary_key,AUTO_INCREMENT"`
    RoleName string
    IsEnable int
}

Below is the db query:

func UpdateRoles(db *gorm.DB, r *models.RoleTypes) (err error) {
    Logr.Debug("Inside UpdateRoles method")

    if err = db.Debug().Model(&r).Where("ID=?", r.ID).Update(&r).Error; err != nil {
        Logr.Error("error occured!!", zap.Any("Error", err))
        return err
    }
    return nil
}

I'm trying to Update the IsEnable to 0 (Zero).

8
  • Maybe IsEnable is actually a boolean in the database? (and if not: why not? a boolean would be the natural choice for a true/false flag)
    – user330315
    Apr 30, 2019 at 6:08
  • IsEnable is an int in db as well. Yeah boolean does the work but im using 0 and 1 globally. @a_horse_with_no_name
    – Saketh Bv
    Apr 30, 2019 at 6:22
  • 1
    Maybe try the tag gorm:"default:0". (doc.gorm.io/crud.html#default-values) "NOTE all fields having zero value, like 0, '', false or other zero values won't be saved into database but will use its default value, it you want to avoid this, consider to use pointer type or scaner/valuer"
    – mkopriva
    Apr 30, 2019 at 6:31
  • 1
    ... or use a map (doc.gorm.io/crud.html#update) "Update with struct only works with none zero values, or use map[string]interface{}".
    – mkopriva
    Apr 30, 2019 at 6:34
  • @mkopriva Using a map[string]interface{} works fine when i am updating all the fields in the struct. But when im updating only "IsEnable" field the remaining fields are updated as blank(existing values are getting erased).
    – Saketh Bv
    Apr 30, 2019 at 6:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.