
最近在使用GORM時,我發現一個問題-外鍵未更新的情況。當我在關聯的表中更新了外鍵欄位的值時,卻沒有同步更新到另一張表中。透過調查和研究,我發現這是因為GORM預設不會自動更新外鍵欄位。這個問題困擾了我一段時間,所以我決定將解決方法分享給大家。在本文中,我將向大家介紹如何使用GORM來正確更新外鍵字段,以避免這個問題。
問題內容
我有兩張桌子,一張是公司
1 2 3 4 5 6 | 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
1 2 3 4 5 6 7 8 | type ProductEntitlement struct {
ID uuid.UUID
CreatedAt 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 的值
更新插入完成後,每次都會插入新行。這是我們正在使用的程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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
#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 中的外鍵未更新的詳細內容。更多資訊請關注PHP中文網其他相關文章!