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中文網其他相關文章!

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。

C 更適合需要直接控制硬件資源和高性能優化的場景,而Golang更適合需要快速開發和高並發處理的場景。 1.C 的優勢在於其接近硬件的特性和高度的優化能力,適合遊戲開發等高性能需求。 2.Golang的優勢在於其簡潔的語法和天然的並發支持,適合高並發服務開發。

Golang在实际应用中表现出色,以简洁、高效和并发性著称。1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Go語言的核心特性包括垃圾回收、靜態鏈接和並發支持。 1.Go語言的並發模型通過goroutine和channel實現高效並發編程。 2.接口和多態性通過實現接口方法,使得不同類型可以統一處理。 3.基本用法展示了函數定義和調用的高效性。 4.高級用法中,切片提供了動態調整大小的強大功能。 5.常見錯誤如競態條件可以通過gotest-race檢測並解決。 6.性能優化通過sync.Pool重用對象,減少垃圾回收壓力。

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

關於SQL查詢結果排序的疑惑學習SQL的過程中,常常會遇到一些令人困惑的問題。最近,筆者在閱讀《MICK-SQL基礎�...

golang ...


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

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

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

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