一七零、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)
相关推荐
orion571 天前
Missing Semester Class1:course overview and introduction of shell
linux
先吃饱再说1 天前
存储的进化:从 MySQL 到浏览器缓存,数据到底住在哪?
数据库
Nturmoils1 天前
字段太多看不全,ksql 的展开模式和输出控制怎么用
数据库·后端
用户120487221611 天前
Linux驱动编译与加载
linux·嵌入式
Databend1 天前
Agent 轨迹分析与归因的数据工程实践
大数据·数据库·agent
这个DBA有点耶1 天前
SQL改写进阶:标量子查询的“隐形代价”与消除实战
数据库·mysql·架构
程序员老赵1 天前
服务器文件不想 SFTP 上传?Docker 跑个 File Browser,浏览器就能管理
服务器·docker·开源
喵个咪1 天前
Go Wind UBA 拆解系列 - 架构总览:三服务、数据流与契约优先
大数据·后端·go
喵个咪1 天前
Go Wind UBA 拆解系列 - 多租户与安全:两套隔离机制的边界
大数据·后端·go
喵个咪1 天前
Go Wind UBA 拆解系列 - OLAP 与 SQL 硬核:25 个分析模型怎么落地
大数据·后端·go