pg icon indicating copy to clipboard operation
pg copied to clipboard

Foreach doesn't reflect hasmany query

Open mwei0210 opened this issue 7 years ago • 3 comments

Was trying to use hasMany field in ForEach but the relation wasn't populated, here is a snippet:

package main

import (
	"fmt"

	"github.com/go-pg/pg"
)

type License struct {
	ID     uint64
	Roster []*Roster
}

type Roster struct {
	LicenseID uint64
	Comment   string
}

func main() {
	db := pg.Connect(&pg.Options{
		User:     "postgres",
	})
	defer db.Close()
	if err := createSchema(db); err != nil {
		panic(err)
	}
	_ = db.Insert(&License{ID: 1})
	_ = db.Insert(&Roster{LicenseID: 1, Comment: "aaa"})
	_ = db.Insert(&Roster{LicenseID: 1, Comment: "bbb"})

	q := db.Model(&License{}).
		Column("license.*", "Roster")
	err := q.ForEach(func(r *License) error {
		fmt.Println("total roster", len(r.Roster)) //supposed to be 2 but there is nothing
		return nil
	})
	if err != nil {
		panic(err)
	}
}

func createSchema(db *pg.DB) error {
	for _, model := range []interface{}{(*License)(nil), (*Roster)(nil)} {
		err := db.CreateTable(model, nil)
		if err != nil {
			return err
		}
	}
	return nil
}

mwei0210 avatar Jan 28 '19 08:01 mwei0210

To addon, after using orm.SetTableNameInflector, doing Join would throw ERROR #42P01 relation "rosters" does not exist because the schema wasn't appended during join

mwei0210 avatar Jan 30 '19 06:01 mwei0210

Ping, is this still an issue with the most recent version?

daemonfire300 avatar Sep 11 '20 07:09 daemonfire300

@daemonfire300 yes, it is still a problem.

Also you should be aware that if this is fixed there will be a query to load has-many relation for each row in the table. Not sure how useful that would be.

vmihailenco avatar Sep 11 '20 08:09 vmihailenco