簡體   English   中英

恐慌:反映:對 GORM .Create() 上的零值調用 reflect.Value.Interface

[英]panic: reflect: call of reflect.Value.Interface on zero Value on GORM .Create()

我是新來的后端,我正在嘗試在表之間建立多對多關系。 我用這個 repo 來制作模型: https ://github.com/harranali/gorm-relationships-examples/tree/main/many-to-many
我將 GORM 與 postgresql 一起使用。
我的模型:

type Book struct {
    gorm.Model
    Title       string         `json:"title"`
    Author      string         `json:"author"`
    Description string         `json:"description"`
    Category    string         `json:"Category"`
    Publisher   string         `json:"publisher"`
    AuthorsCard []*AuthorsCard `gorm:"many-to-many:book_authorscard;" json:"authorscard"`
}

type AuthorsCard struct {
    gorm.Model
    Name        string `json:"name"`
    Age         int    `json:"age"`
    YearOfBirth int    `json:"year"`
    Biography   string `json:"biography"`
}

連接到數據庫並自動遷移后:

func init() {
    config.Connect()
    db = config.GetDB()
    db.AutoMigrate(&models.Book{}, &models.AuthorsCard{})
}

我創建了 Function 來查看這種關系是如何工作的:

func TestCreate() {

var AuthorsCard = []models.AuthorsCard{
        {
            Age:         23,
            Name:        "test",
            YearOfBirth: 1999,
            Biography:   "23fdgsdddTEST",
        },
    }
    db.Create(&AuthorsCard)
    var testbook = models.Book{
        Title:       "Test",
        Author:      "tst",
        Description: "something",
    }
    db.Create(&testbook)

    db.Model(&testbook).Association("AuthorsCard").Append(&AuthorsCard)
} 

但是得到了這個錯誤:恐慌:反映:在零值上調用 reflect.Value.Interface [恢復]恐慌:反映:在零值上調用 reflect.Value.Interface

我該如何處理這個“空”問題並建立適當的關系?

UPD:問題的第一部分與GORM的版本有關,在我將舊版本(github.com/jinzhu/gorm v1.9.16)更改為新版本(gorm.io/gorm v1.23.6)后,反映的問題錯誤消失了。 但是現在,當我想創建新書時,出現此錯誤:

/go/pkg/mod/gorm.io/driver/postgres@v1.3.7/migrator.go:119 錯誤:沒有唯一約束匹配給定鍵的引用表“authors_cards”(SQLSTATE 42830)[28.440ms] [rows :0]創建表“book_authorscard”(“book_id”bigint,“authors_card_id”bigint,主鍵(“book_id”,“authors_card_id”),約束“fk_book_authorscard_authors_card”外鍵(“authors_card_id”)參考“authors_cards”(“id” ),CONSTRAINT "fk_book_authorscard_book" FOREIGN KEY ("book_id") REFERENCES "books"("id")) [GIN-debug] [WARNING] 創建一個 Engine 實例,其中已經附加了 Logger 和 Recovery 中間件。

UPD 2 :我決定制作一個 Migrator().DropTable()。 這有點奏效,所有錯誤都消失了。 但我仍然得到 "authorscard": null 作為回應。

通過閱讀 Gorm v2 ( https://gorm.io/docs/v2_release_note.html ) 的發行說明,我認為您正在嘗試將 v2 功能與舊版本 (<v2) 一起使用。 嘗試使用 Gorm 最新版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM