Golang go-pg关系递归查询

标签 go go-pg

我需要递归加入,像这样:

SELECT a.*, b.* c.* FROM a
LEFT JOIN b on b.id = a.b_id
LEFT JOIN c ON c.id = b.c_id

我的模型定义是:

type A struct {
    ID int,
    NameA string,
    B_id int
    B *B,
    C *C,
}

type B struct {
    ID int,
    C_id int,
    NameB string,
    C C,
}

type C struct {
    ID int,
    NameC string,
}

我尝试使用关系但没有用:

a := A{}
//does not work
db.Model(&a).Relation("B").Relation("C").First()

//works
db.Model(&a).Relation("B").First()

我如何在 go-pg 上实现递归连接,如果有人有这方面的经验,请告诉我。非常感谢。

最佳答案

您需要指出它实际上是第二个结构上的关系:

db.Model(&a).Relation("B").Relation("B.C").First()

关于Golang go-pg关系递归查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54083904/

相关文章:

image-processing - 我可以修改图像的像素值吗?

database - 由于这种模式,在同一个结构中使用事务和简单的数据库连接我该怎么办?

postgresql - 加入时列引用不明确

mysql - golang 现在用松鼠更新设置时间

go - 作家片段与作家指针

去嵌入 : method not inherited

Go, Golang : array type inside struct, 缺少类型复合文字

postgresql - 使用 ORM 将任意数据检索到嵌套对象中

go-pg "belongs to"2个字段到同一个表