目錄
問題內容
解決方法
首頁 後端開發 Golang Gorm:無法新增或更新子行 - 外鍵約束在自引用時失敗

Gorm:無法新增或更新子行 - 外鍵約束在自引用時失敗

Feb 09, 2024 am 09:18 AM

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

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
Golang vs. Python:性能和可伸縮性 Golang vs. Python:性能和可伸縮性 Apr 19, 2025 am 12:18 AM

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

Golang和C:並發與原始速度 Golang和C:並發與原始速度 Apr 21, 2025 am 12:16 AM

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

Golang的影響:速度,效率和簡單性 Golang的影響:速度,效率和簡單性 Apr 14, 2025 am 12:11 AM

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

開始GO:初學者指南 開始GO:初學者指南 Apr 26, 2025 am 12:21 AM

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

Golang vs.C:性能和速度比較 Golang vs.C:性能和速度比較 Apr 21, 2025 am 12:13 AM

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。

Golang vs. Python:主要差異和相似之處 Golang vs. Python:主要差異和相似之處 Apr 17, 2025 am 12:15 AM

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。

Golang和C:性能的權衡 Golang和C:性能的權衡 Apr 17, 2025 am 12:18 AM

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

C和Golang:表演至關重要時 C和Golang:表演至關重要時 Apr 13, 2025 am 12:11 AM

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

See all articles