简体   繁体   中英

Update with 0 value using Gorm

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!!

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM