最近在使用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.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 的值
更新插入完成後,每次都會插入新行。這是我們正在使用的程式碼
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 中的外鍵未更新的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

開發者應遵循以下最佳實踐:1.謹慎管理goroutines以防止資源洩漏;2.使用通道進行同步,但避免過度使用;3.在並發程序中顯式處理錯誤;4.了解GOMAXPROCS以優化性能。這些實踐對於高效和穩健的軟件開發至關重要,因為它們確保了資源的有效管理、同步的正確實現、錯誤的適當處理以及性能的優化,從而提升軟件的效率和可維護性。

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

我們需要自定義錯誤類型,因為標準錯誤接口提供的信息有限,自定義類型能添加更多上下文和結構化信息。 1)自定義錯誤類型能包含錯誤代碼、位置、上下文數據等,2)提高調試效率和用戶體驗,3)但需注意其複雜性和維護成本。

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

WebStorm Mac版
好用的JavaScript開發工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。