一七零、GORM值为0或者空字符串的时候不能被更新&创建的五种解决办法

在使用grom时,如果用结构体的形式,对数据库进行更新时,会出现一个问题:当我们想要将某个字段的值更新为0&空字符串,执行update之后会发现该数据实际上并没有被更新。

例如有如下数据表:

id name score desc
1 王五 99 调皮

有如下结构体:

复制代码
type Student struct{
	Id    int32 `gorm:"type:int(11);column:id;primaryKey;autoIncrement;comment:" json:"id"`
	Name  string `gorm:"type:varchar(100);column:name;not null;default:'';comment:姓名"`
	Score int32 `gorm:"type:int(11);column:score;comment:分数"`
	Desc  string `gorm:"type:varchar(1000);column:desc;default:'';comment:备注"`
}

当我们执行以下操作后

复制代码
upStudent := Student{
	Id    :1,
	Name  :张三,
	Score :0,
	Desc:""
}

db.Model(&student).Where("id=?", Student.Id).Updates(Student)

会发现,执行成功之后,score依旧等于99,Desc也是"调皮"

解决方法一:结合 Select 和 Omit

复制代码
fields := []string{"id","name","score","desc"}
db.Model(&Student).Select(fields).Where("id=?", Student.Id).Updates(Student)
// 或者Omit
db.Model(&Student{}).Omit("id").Where("id = ?", upStudent.Id).Updates(upStudent)

解决方法二:使用Save

注:Save 会保存所有的字段,即使字段是零值;保存是一个组合函数。 如果保存值不包含主键,它将执行 Create,否则它将执行 Update (包含所有字段)。

复制代码
db.Model(&Student).Where("id=?", Student.Id).Save(Student)

解决方法三:使用map接口,即mapstringinterface{} (推荐)

注:我们使用的是protobuf定义了的结构时,转换成map有些许麻烦。

复制代码
values := map[string]interface{}{
				"id":          upStudent.Id,
				"name":      upStudent.Name,
				"score":   upStudent,Score,
				"desc":upStudent,Desc,
		}
db.Model(&Student).Where("id=?", Student.Id).Updates(values)

解决方法三:使用map接口,即mapstringinterface{} (推荐)

注:我们使用的是protobuf定义了的结构时,转换成map有些许麻烦。

复制代码
values := map[string]interface{}{
				"id":          upStudent.Id,
				"name":      upStudent.Name,
				"score":   upStudent,Score,
				"desc":upStudent,Desc,
		}
db.Model(&Student).Where("id=?", Student.Id).Updates(values)

解决方法四:逐字段单独赋值

注:我们使用的是protobuf定义了的结构时,转换成map有些许麻烦。

复制代码
upStudent := Student{
	Id    : 1,
}

db.Model(&Student{}).Where("id = ?", upStudent.Id).Update("score", 0).Update("name", "张三").Update("desc", "")

解决方法五:定义 Struct 时将字段设置为指针类型

通过将字段定义为指针类型,可以避免默认忽略 0 值的问题。同样适用于空字符串。

复制代码
score := int32(0)
name := "张三"
desc := ""
upStudent := Student{
	Id    : 1,
	Name  : &name,
	Score : &score,
	Desc: &desc,
}
db.Model(&Student{}).Where("id = ?", upStudent.Id).Updates(upStudent)
相关推荐
明月_清风33 分钟前
从二叉树到 B+ 树:一文搞懂工程中「树」的演化之道
数据结构·算法·go
fpcc35 分钟前
计算机原理—Linux是如何加载可执行文件到内存
linux
野熊佩骑35 分钟前
Kubernetes实战系列文章(三) 之 K8S运维常用命令
linux·运维·docker·微服务·云原生·容器·kubernetes
码农客栈1 小时前
linux 设备树下的 platform 驱动编写
linux
小HANN1 小时前
Linux建站实战:CentOS7+LNMP 从零部署 ECShop 开源电商系统
linux·运维·服务器·经验分享
做运维的阿瑞1 小时前
Shell 脚本经典十三问:引号、变量、子 Shell 与重定向一次讲清问:引号、变量、子 Shell 与重定向一次讲清
linux·tcp/ip
昌原的儿子LEO1 小时前
Linux IO多路复用与SQLite数据库核心知识点总结
linux·数据库·oracle
GeW1 小时前
RHCE通关秘籍:从零基础到高分拿证的5个加速器
linux
三8441 小时前
SSRF 从入门到实战:原理、危害与基础利用
服务器·网络安全·ssrf·#web安全
江湖十年2 小时前
在 Go 中使用 dyno 包处理动态对象
后端·面试·go