Search code examples
gogo-gorm

Panic when attempting to use GORM Joins Preloading


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:[email protected]: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.


Solution

  • According to docs (Joins Preloading):

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