英文:
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 one
,belongs to
英文:
According to docs (Joins Preloading):
> NOTE Join Preload
works with one-to-one relation, e.g: has one
, belongs to
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论