与关系查询的关系

relation with relation query

有三个table表A、表B、表C和一个结点table如下定义如下:

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

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

最后,

 type TableC struct {
   ID int
   Name string
  }

table_a_table_b 是一个连接点 table,它将 TableA 和 TableB 与多对多关系相关联。

到目前为止一切顺利,我可以 select TableA 中的数据如下:

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

然而,结果并不是我想要的。它导致这样的事情:

 [
  {
   "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
      }
    }
  ]

在阅读了一些提示后,我开始在关系中使用查询函数。这是我所做的:

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

但我收到了以下详细信息的恐慌:

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/pg@v8.0.6+incompatible/orm/model_table.go:73 (0x701adc) newTableModelIndex: typ := typeByIndex(root.Type(), index) /home/davood/dev/pkg/mod/github.com/go-pg/pg@v8.0.6+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/pg@v8.0.6+incompatible/orm/model_table_slice.go:57 (0x703f7c) (*sliceTableModel).Join: return m.join(m.Value(), name, apply)

经过一些搜索和我应该归功于报告的 go-pgs github 问题,我得出了这个解决方案:

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

给你!