尝试使用GORM的预加载时出现恐慌错误。

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

Panic when attempting to use GORM Joins Preloading

问题

我正在尝试使用Go创建一个简单的REST API作为学习项目。在尝试使用GORM的Joins预加载功能填充has many关系时遇到了问题。

据我所知,我已经正确设置了关系,数据库中的表结构看起来也不错,并且记录已经插入,但是以下代码会产生一个错误:

panic: reflect: call of reflect.Value.Field on slice Value

我在这里提供了一个最小化的示例来展示我的问题:

package main

import (
	"log"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type Page struct {
	gorm.Model
	Text   string
	BookID uint
}

type Book struct {
	gorm.Model
	Pages []Page
}

func main() {
	db, err := gorm.Open(postgres.Open("postgres://postgres:password@host.docker.internal:5432/postgres"), &gorm.Config{})
	if err != nil {
		log.Fatal(err.Error())
	}
	db.AutoMigrate(&Book{})
	db.AutoMigrate(&Page{})
	db.Create(&Book{
		Pages: []Page{
			{Text: "Page One"},
		},
	})
	result := []Book{}
	// 这里出错了
	db.Joins("Pages").Find(&result)

	// 运行正常
	// db.Preload("Pages").Find(&result)
}

非常感谢您对我犯错的指导,我对Go还是很新手。

英文:

I'm attempting to create a simple REST API using go as a learning project. I've run into a snag while trying to populate a has many relationship using the Joins preload feature of GORM.

As far as I can tell, I have set up the relationships properly, the table structure looks good in the db and the records get inserted, but the following code produces an error:

panic: reflect: call of reflect.Value.Field on slice Value

I've produced a minimal example here showing my issue

package main

import (
	"log"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type Page struct {
	gorm.Model
	Text   string
	BookID uint
}

type Book struct {
	gorm.Model
	Pages []Page
}

func main() {
	db, err := gorm.Open(postgres.Open("postgres://postgres:password@host.docker.internal:5432/postgres"), &gorm.Config{})
	if err != nil {
		log.Fatal(err.Error())
	}
	db.AutoMigrate(&Book{})
	db.AutoMigrate(&Page{})
	db.Create(&Book{
		Pages: []Page{
			{Text: "Page One"},
		},
	})
	result := []Book{}
	// errors here
	db.Joins("Pages").Find(&result)

	// works fine
	// 	db.Preload("Pages").Find(&result)
}

Any guidance on where I'm going wrong would be much appreciated, brand new to go.

答案1

得分: 5

根据文档(Joins Preloading):

> 注意 Join Preload 适用于一对一关系,例如:has onebelongs to

英文:

According to docs (Joins Preloading):

> NOTE Join Preload works with one-to-one relation, e.g: has one, belongs to

huangapple
  • 本文由 发表于 2021年9月6日 18:35:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/69073133.html
匿名

发表评论

匿名网友

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

确定