恐慌:反射:在 GORM .Create() 上调用 reflect.Value.Interface 的零值。

huangapple go评论75阅读模式
英文:

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

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我刚开始学习Go和后端开发,我正在尝试在表之间建立多对多的关系。我使用了这个仓库来创建模型: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:"many2many: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{})
}

我创建了一个函数来查看这个关系是如何工作的:

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)
}

但是出现了以下错误:
panic: reflect: call of reflect.Value.Interface on zero Value [recovered]
panic: reflect: call of reflect.Value.Interface on zero Value

我该如何处理这个"Null"问题并建立正确的关系?

**更新:**问题的第一部分与GORM的版本有关。在将旧版本(github.com/jinzhu/gorm v1.9.16)更改为新版本(gorm.io/gorm v1.23.6)后,reflect错误的问题消失了。但是现在,当我想创建新的书籍时,出现了以下错误:

/go/pkg/mod/gorm.io/driver/postgres@v1.3.7/migrator.go:119 ERROR: there is no unique constraint matching given keys for referenced table "authors_cards" (SQLSTATE 42830)
[28.440ms] [rows:0] CREATE TABLE "book_authorscard" ("book_id" bigint,"authors_card_id" bigint,PRIMARY KEY ("book_id","authors_card_id"),CONSTRAINT "fk_book_authorscard_authors_card" FOREIGN KEY ("authors_card_id") REFERENCES "authors_cards"("id"),CONSTRAINT "fk_book_authorscard_book" FOREIGN KEY ("book_id") REFERENCES "books"("id"))
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

**更新2:**我决定使用Migrator().DropTable()来删除表,这样做有点奏效,所有的错误都消失了。但是我仍然得到"authorscard": null作为响应。

英文:

I'm new to go and Backend and I'm Trying to make many-to-many relation between tables. I used this repo to make model:https://github.com/harranali/gorm-relationships-examples/tree/main/many-to-many
I Used GORM with postgresql.
My model:

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"`
}

After connecting to database and AutoMigrating:

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

I've created Function to see how that relation works:

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)
} 

But got This Error:
panic: reflect: call of reflect.Value.Interface on zero Value [recovered]
panic: reflect: call of reflect.Value.Interface on zero Value

How can I deal with this "Null" problem and make proper relation?

UPD: The First part of a problem was connected to a version of GORM, After I changed old version(github.com/jinzhu/gorm v1.9.16) to new version (gorm.io/gorm v1.23.6) the problem with reflect Error gone.
but now, when I want to create new book, I get this Error:

/go/pkg/mod/gorm.io/driver/postgres@v1.3.7/migrator.go:119 ERROR: there is no unique constraint matching given keys for referenced table "authors_cards" (SQLSTATE 42830)
[28.440ms] [rows:0] CREATE TABLE "book_authorscard" ("book_id" bigint,"authors_card_id" bigint,PRIMARY KEY ("book_id","authors_card_id"),CONSTRAINT "fk_book_authorscard_authors_card" FOREIGN KEY ("authors_card_id") REFERENCES "authors_cards"("id"),CONSTRAINT "fk_book_authorscard_book" FOREIGN KEY ("book_id") REFERENCES "books"("id"))
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

UPD 2:
I decided to make a Migrator().DropTable(). That's kinda worked, and all Errors have gone. But still I get "authorscard": null as a response.

答案1

得分: 1

通过阅读 Gorm v2 的发布说明(https://gorm.io/docs/v2_release_note.html),我认为你正在尝试使用一个旧版本(<v2)的 Gorm 来使用 v2 的功能。请尝试使用 Gorm 的最新版本。

英文:

By reading the release note of Gorm v2 (https://gorm.io/docs/v2_release_note.html), I think that you are trying to use v2 feature with an old version (<v2). Try to use Gorm latest version.

huangapple
  • 本文由 发表于 2022年6月23日 18:39:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/72728791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定