relation with relation query

1.5k Views Asked by At

Having three tables, TableA, TableB, TableC and one junction table as below defined as below:

type TableA struct {
   ID int
   Name string
   TableBs []*TableB  `pg:",many2many:table_a_table_b"`
 }

and

type TableB struct{
  ID int
  Name string
  TableAID int
  TableA *TableA
  TableCID int
  TableC *TableC
}

finally,

 type TableC struct {
   ID int
   Name string
  }

table_a_table_b is a junction table that relates TableA and TableB with many2many relation.

So far so good, I can select the data in TableA as below:

 pgdb := pg.Connect(......)
 tableA := []TableA{}
 
 pgd.Model(&tableA).Relation("TableBs").Select()

The result, however, is not what I exactly want. It leads to something like this:

 [
  {
   "Id": 1
   "Name": "TestA record"
   "TableBs": [
      {
         "Id": 1,
         "Name": "TestB record",
         "TableAID": 1,
         "TableCID": 1, //Here, I want to have some extra info about TableC
      }
    }
  ]

After reading some hints, I took to use query function inside relations. Here's what I did:

 pgdb.Model(&tableA).Relation("TableBs",func(q *orm.Query) (*orm.Query, error) {
   return q.Relation("TableC"), nil
 }).Select()

But I received a panic with the following details:

reflect: call of reflect.Value.Type on zero Value /usr/local/go/src/reflect/value.go:1877 (0x4b5245) Value.Type: panic(&ValueError{"reflect.Value.Type", Invalid}) /home/davood/dev/pkg/mod/github.com/go-pg/[email protected]+incompatible/orm/model_table.go:73 (0x701adc) newTableModelIndex: typ := typeByIndex(root.Type(), index) /home/davood/dev/pkg/mod/github.com/go-pg/[email protected]+incompatible/orm/model_table_struct.go:328 (0x707a10) (*structTableModel).join: model, err := newTableModelIndex(bind, index, rel) /home/davood/dev/pkg/mod/github.com/go-pg/[email protected]+incompatible/orm/model_table_slice.go:57 (0x703f7c) (*sliceTableModel).Join: return m.join(m.Value(), name, apply)

1

There are 1 best solutions below

0
On BEST ANSWER

After some searches and the credit I should give to reprted go-pg's github issues, I came to this solution:

pgd.Model(&tableA).Relation("TableBs").Relation("TableBs.TableC").Select()

There you go!