Gorm:無法新增或更新子行 - 外鍵約束在自引用時失敗
php小編新一在開發過程中,有時會遇到"無法新增或更新子行 - 外鍵約束在自引用時失敗"的錯誤。這個錯誤通常發生在資料庫中存在自引用的情況下,例如一個表格中的某個欄位引用了表格中的另一個欄位。在這種情況下,如果外鍵約束沒有正確配置,就會導致無法新增或更新子行的錯誤。接下來,我們將介紹一些解決這個問題的方法。
問題內容
我有一個如下所示的結構:
type category struct { code *int `gorm:"unique;primarykey;"` parentcategory *category `gorm:"foreignkey:code"` }
類別本身可以有一個parentcategory,它也來自類別類型。所以它引用了它自己。 如果它是第一個類別,則它沒有父類別。
我有一個包含 4 個類別的數組,如上所述,第一個沒有 ab parentcategory。
當一個接一個地保存這些類別時(從第一個沒有 parentcategory 開始,我收到這些錯誤(只需在此處列印前兩個):
Error 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`ps_product_service`.`categories`, CONSTRAINT `fk_categories_parent_category` FOREIGN KEY (`code`) REFERENCES `categories` (`code`)) [20.890ms] [rows:0] INSERT INTO `categories` (`code`) VALUES (0) RETURNING `code` Error when creating category: Error 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`ps_product_service`.`categories`, CONSTRAINT `fk_categories_parent_category` FOREIGN KEY (`code`) REFERENCES `categories` (`code`))&{Code:0x140003c6a00 ParentCategory:<nil>} 2023/06/19 21:31:44 Error 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`ps_product_service`.`categories`, CONSTRAINT `fk_categories_parent_category` FOREIGN KEY (`code`) REFERENCES `categories` (`code`)) [7.689ms] [rows:0] INSERT INTO `categories` (`code`) VALUES (99) RETURNING `code` Error when creating category: Error 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`ps_product_service`.`categories`, CONSTRAINT `fk_categories_parent_category` FOREIGN KEY (`code`) REFERENCES `categories` (`code`))&{Code:0x140003c6a20 ParentCategory:<nil>}
我真的不知道我必須在這裡做什麼。有人可以幫我解決這個問題嗎?
解決方法
我應該使用以下程式碼來管理您的需求:
package main import ( "fmt" "github.com/samber/lo" "gorm.io/driver/postgres" "gorm.io/gorm" ) type category struct { code uint `gorm:"unique;primarykey;"` parentcategoryid *uint parentcategory *category `gorm:"foreignkey:parentcategoryid"` } func main() { dsn := "host=localhost port=54322 user=postgres password=postgres dbname=postgres sslmode=disable" db, err := gorm.open(postgres.open(dsn)) if err != nil { panic(err) } db.automigrate(&category{}) // load dummy data db.create(&category{ code: 1, parentcategoryid: nil, }) db.create(&category{ code: 2, parentcategoryid: lo.toptr[uint](1), }) db.create(&category{ code: 3, parentcategoryid: lo.toptr[uint](2), }) db.create(&category{ code: 4, parentcategoryid: lo.toptr[uint](1), }) // reading logic var categories []category if err := db.model(&category{}).find(&categories).error; err != nil { panic(err) } for _, v := range categories { if v.parentcategoryid == nil { fmt.printf("id: %v\tparentcategoryid: <nil>\n", v.code) continue } fmt.printf("id: %v\tparentcategoryid: %v\n", v.code, *v.parentcategoryid) } }
如果我了解了您的需求,您需要有一個引用自身的表格。這就是為什麼我以這種方式定義 category
結構。每個類別都有自己的 parentcategoryid
除非該類別沒有父級。如果您嘗試執行前面的程式碼,您應該得到以下結果:
id: 1 parentCategoryId: <nil> id: 2 parentCategoryId: 1 id: 3 parentCategoryId: 2 id: 4 parentCategoryId: 1
也許我沒有從你的問題中得到什麼,如果是這樣的話請告訴我,我會更新我的答案,謝謝!
以上是Gorm:無法新增或更新子行 - 外鍵約束在自引用時失敗的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

Go語言中用於浮點數運算的庫介紹在Go語言(也稱為Golang)中,進行浮點數的加減乘除運算時,如何確保精度是�...

Go爬蟲Colly中的Queue線程問題探討在使用Go語言的Colly爬蟲庫時,開發者常常會遇到關於線程和請求隊列的問題。 �...

後端學習路徑:從前端轉型到後端的探索之旅作為一名從前端開發轉型的後端初學者,你已經有了nodejs的基礎,...

本文討論了GO編程中的GO FMT命令,該命令將代碼格式化以遵守官方樣式準則。它突出了GO FMT在維持代碼一致性,可讀性和降低樣式辯論方面的重要性。 FO的最佳實踐

本文介紹在Debian系統下監控PostgreSQL數據庫的多種方法和工具,助您全面掌握數據庫性能監控。一、利用PostgreSQL內置監控視圖PostgreSQL自身提供多個視圖用於監控數據庫活動:pg_stat_activity:實時展現數據庫活動,包括連接、查詢和事務等信息。 pg_stat_replication:監控複製狀態,尤其適用於流複製集群。 pg_stat_database:提供數據庫統計信息,例如數據庫大小、事務提交/回滾次數等關鍵指標。二、借助日誌分析工具pgBadg
