首頁 > 後端開發 > Golang > 主體

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

王林
發布: 2024-02-09 09:18:10
轉載
1090 人瀏覽過

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

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!