最近在使用GORM时,我发现一个问题——外键未更新的情况。当我在关联的表中更新了外键字段的值时,却没有同步更新到另一张表中。通过调查和研究,我发现这是因为GORM默认情况下不会自动更新外键字段。这个问题困扰了我一段时间,所以我决定将解决方法分享给大家。在本文中,我将向大家介绍如何使用GORM来正确更新外键字段,以避免出现这个问题。
问题内容
我有两张桌子,一张是公司
type Company struct { Id uuid.UUID `gorm:"column:id;primaryKey;"` CreatedAt time.Time `gorm:"index;column:createdAt"` UpdatedAt time.Time `gorm:"index;column:updatedAt"` Name string `gorm:"column:name" binding:"required"`}
登录后复制
另一个是product_entitlement
type ProductEntitlement struct {ID uuid.UUIDCreatedAt time.Time `gorm:"index;column:createdAt"`UpdatedAt time.Time `gorm:"index;column:updatedAt"`Type string `gorm:"column:type" binding:"required"`CompanyID uuid.UUID `gorm:"column:companyId;size:36"`Company Company `gorm:"foreignKey:CompanyID"`}
登录后复制
CompanyID 是外键。 CompanyID 包含来自 Company.Id 的值
更新插入完成后,每次都会插入新行。这是我们正在使用的代码
func UpdateEntitlement(c *gin.Context) {cid := c.Param("companyId") id := c.Param("entitlementId") eid := uuid.MustParse(id) log.Println(eid) uid := uuid.MustParse(cid) log.Println(uid) var entitlementRequest entities.ProductEntitlement if err := c.BindJSON(&entitlementRequest); err != nil { log.Println(err) fmt.Println("ERROR: ", err) c.JSON(400, gin.H{"error": "Invalid JSON format"}) return } if err := database.DB.Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "id"}}, UpdateAll: true, }).Create(&entitlementRequest).Error; err != nil { log.Println(err) }}
登录后复制
但它总是失败并给出错误
BD820BD3F94A2A45E18ED8E8094EF395
如果 ID 存在,我想更新 Product_entitlement,否则创建一个新的
网址如下,http://localhost:8080/company/{{companyId}}/product/{{companyId}} 并使用 PUT 方法身体是
{“类型”:“自动”}
解决方法
如果它对某人有帮助,我们可以使用 FirstOrCreate 函数来检查 id 是否存在并进行更新,如果不存在则创建一个新的。
要分配外键,我们需要将值分配给相关表,
entitlementRequest.CompanyID = uid
func UpdateEntitlement(c *gin.Context) { cid := c.Param("companyId") uid := uuid.MustParse(cid) eid := c.Param("entitlementId") nid := uuid.MustParse(eid) var entitlementRequest entities.ProductEntitlement entitlementRequest.CompanyID = uid if err := c.BindJSON(&entitlementRequest); err != nil { fmt.Println("ERROR: ", err) c.JSON(400, gin.H{"error": "Invalid JSON format"}) return } if err := database.DB.Where("id = ?", nid). Assign(entitlementRequest). FirstOrCreate(&entitlementRequest).Error; err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"}) return } c.JSON(http.StatusOK, gin.H{"error": "Product entitlement upserted successfully"})}
登录后复制
以上就是GORM 中的外键未更新的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2357498.html