5

I am trying to update some values using gorm library but bytes and ints with 0 value are not updated

var treatment model.TreatmentDB

err = json.Unmarshal(b, &treatment)
if err != nil {
    http.Error(w, err.Error(), 500)
    return
}

fmt.Println(&treatment)

db := db.DB.Table("treatment").Where("id = ?", nID).Updates(&treatment)

this print value is {0 3 1 0 0 0 2018-01-01 4001-01-01} and those 0 are the byte value (tinyint(1) in database, if I change to int also not working) which are not updated, the rest of values work fine

if I update them without using Gorm this way it's working perfectly with 0 values

var query  = fmt.Sprintf("UPDATE `pharmacy_sh`.`treatment` SET `id_med` = '%d', `morning` = '%d', `afternoon` = '%d', `evening` = '%d', `start_treatment` = '%s', `end_treatment` = '%s' WHERE (`id` = '%s')", treatment.IDMed, treatment.Morning,  treatment.Afternoon, treatment.Evening, treatment.StartTreatment, treatment.EndTreatment, nID)

update, err := dbConnector.Exec(query)

and this is my model obj

type TreatmentDB struct {
gorm.Model
ID              int         `json:"id"`
IDMed           int         `json:"id_med"`
IDUser          int         `json:"id_user"`
Morning         byte        `json:"morning"`
Afternoon       byte        `json:"afternoon"`
Evening         byte        `json:"evening"`
StartTreatment  string      `json:"start_treatment"`
EndTreatment    string      `json:"end_treatment"`
}

Thanks for any help!!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Pablo R.
  • 711
  • 2
  • 10
  • 31

3 Answers3

5

I found a very tricky way to solve this problem.You just need to change your struct field type into a ptr.

change

type Temp struct{
String string
Bool bool
}

to

type Temp struct{
String *string
Bool *bool
}
Jonyhy96
  • 168
  • 1
  • 2
  • 10
  • If you don't want to change your struct definitions you can go with this solution (converting struct to map) as well: https://stackoverflow.com/questions/64330504/update-method-does-not-update-zero-value – Heikkisorsa Oct 13 '20 at 11:51
  • 1
    But wouldn't this will allow `nil` as a valid value? Which we may not want – hashlash Nov 02 '20 at 03:30
1

if you wish save zero you must to write "Select" and put the column to change

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

reference: https://gorm.io/docs/update.html#Update-Selected-Fields

0

I think, this is also possible way, how to do it:

var t TreatmentDB 
db.Find(&t).Where("id = ?", 1)
t.IDUser = 0
db.Save(t)
mk nv
  • 41
  • 4