当前位置:网站首页>gorm 无法更新带有外键的字段
gorm 无法更新带有外键的字段
2022-08-07 00:22:00 【dorlolo】
问题说明
代码缩减后大致如下
首先定义了一个表结构体,关键点是ContactPersonId作为外键关联到ServiceUsers 表
type ParticipatingUnits struct {
global.GVA_MODEL
Name string `gorm:"column:name"`
ContactPersonId uint ` gorm:"column:contact_person_id"`
ContactPersonInfo ServiceUsers `gorm:"foreignKey:ContactPersonId;references:ID"`
ContactName string `gorm:"column:contact_name`
}
然后使用Preload和First方法获取值,并做修改,最后使用save方法保存
var participatingUnits model.ParticipatingUnits
global.GVA_DB.Preload("ContactPersonInfo").Where("id = 1").First(&participatingUnits )
participatingUnits .ContactName= "张三"
participatingUnits .ContactPersonId= 2
global.GVA_DB.Save(&participatingUnits)
最终结果,ContactName更新成功。ContactPersonId 还是之前的值。这就很费解,又尝试了updates方法,还是不行。
解决方案
最后发现两种方案可以解决这个问题
- 清楚外键引用的数据,然后再保存
global.GVA_DB.Model(&enterpriseInfo).Association("ContactPersonInfo").Clear()
global.GVA_DB.Save(&participatingUnits)
Association("ContactPersonInfo").Clear()这个方法,应该是enterpriseInfo.ContactPersonInfo中的值给清空了。我怀疑把enterpriseInfo.ContactPersonInfo.ID主键改成2问题也能解决(外键和外键引用的数据保持一致)。因为没时间试,感兴趣的朋友可以测试一下。
- 查询的时候把
Preload方法去掉
//global.GVA_DB.Preload("ContactPersonInfo").Where("id = 1").First(&participatingUnits )
global.GVA_DB.Where("id = 1").First(&participatingUnits )
边栏推荐
猜你喜欢

2022年P气瓶充装考试试题及答案

Understanding of data type float storage structure

leetcode 22. 括号生成

【kali-漏洞利用】(3.4)免杀Payload 生成工具(下):Veil后门使用、监听失败原因

leetcode 20. 有效的括号

数学英语题目理解模型记录(1)

自动化测试真的有被需要吗?

倒计时3天|2022 OceanBase 年度发布会亮点抢先看!

新库上线 | CnOpenData 新三板公司专利及引用被引用数据

What is the matter with several IP addresses of this machine?to analyze
随机推荐
关于接口的安全性测试,这几点你必须掌握
今日睡眠质量记录70分
数据类型float存储结构的理解
2022年电工(初级)特种作业证考试题库及模拟考试
图注意力机制理解
国内Api行业,可以内卷到什么程度?
[1408. String matching in arrays]
手撕 Android Framework底层面试题集合
安静的思考
超分辨率模型小抄(1)
mysql数据库中select 基本查询(1)
What is the matter with several IP addresses of this machine?to analyze
【Day_13 0509】Parameter analysis
jvm总结
js中的原型与原型链
A Preliminary Study of Web Development: The Box Model of Web Page Layout
ICCV何恺明团队又一神作:Transformer仍有继续改善的空间
Distillation Learning Framework Cheat Sheet (1)
多项式——多项式除法
[Redis] Redis Learning - Five Basic Data Types