pg
pg copied to clipboard
Foreach doesn't reflect hasmany query
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
}
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
Ping, is this still an issue with the most recent version?
@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.