具有以下三个表,TableA,TableB,TableC 和一个连接表,定义如下:
type TableA struct {
ID int
Name string
TableBs []*TableB `pg:",many2many:table_a_table_b"`
}
Run Code Online (Sandbox Code Playgroud)
和
type TableB struct{
ID int
Name string
TableAID int
TableA *TableA
TableCID int
TableC *TableC
}
Run Code Online (Sandbox Code Playgroud)
最后,
type TableC struct {
ID int
Name string
}
Run Code Online (Sandbox Code Playgroud)
table_a_table_b 是一个连接表,将表 A 和表 B 与多对多关系关联起来。
到目前为止一切顺利,我可以选择 TableA 中的数据,如下所示:
pgdb := pg.Connect(......)
tableA := []TableA{}
pgd.Model(&tableA).Relation("TableBs").Select()
Run Code Online (Sandbox Code Playgroud)
然而,结果并不是我真正想要的。它导致这样的事情:
[
{
"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
}
}
]
Run Code Online (Sandbox Code Playgroud)
在阅读了一些提示后,我开始在关系中使用查询功能。这是我所做的:
pgdb.Model(&tableA).Relation("TableBs",func(q *orm.Query) (*orm.Query, error) {
return q.Relation("TableC"), nil
}).Select()
Run Code Online (Sandbox Code Playgroud)
但是我收到了以下详细信息的恐慌:
反映:在零上调用reflect.Value.Type 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: 模型,错误: = 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)
经过一些搜索和我应该对 reprted go-pg 的 github 问题给予的信任,我来到了这个解决方案:
pgd.Model(&tableA).Relation("TableBs").Relation("TableBs.TableC").Select()
Run Code Online (Sandbox Code Playgroud)
你去吧!
| 归档时间: |
|
| 查看次数: |
346 次 |
| 最近记录: |