使用Gorm以0值更新 [英] Update with 0 value using Gorm

查看:276
本文介绍了使用Gorm以0值更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用gorm库更新某些值,但不会更新具有0值的字节和整数

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)

此打印值是{0 3 1 0 0 0 2018-01-01 4001-01-01},而这些0是字节值(数据库中的tinyint(1),如果我更改为int也不起作用)没有更新,其余的值都可以正常工作

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

如果我在不使用Gorm的情况下更新它们,则可以完美地使用0值

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)

这是我的模型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"`
}

感谢您的帮助!

推荐答案

我发现了解决此问题的非常棘手的方法.您只需将struct字段类型更改为ptr.

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

更改

type Temp struct{
String string
Bool bool
}

type Temp struct{
String *string
Bool *bool
}

这篇关于使用Gorm以0值更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆