How to handle joins with gorp?

huangapple go评论98阅读模式
英文:

How to handle joins with gorp?

问题

在我的一个业余项目中,我有一个这样的结构体:

type Resource struct {
    Id int
    ParentIds []int
    Title string
    Contents []byte
    Resources []Resource
}

每个资源可能有一些子资源([]Resource)。我想通过使用一个类似于gorp的查询到结构体映射器来开始,但我不知道如何映射这样的查询:

SELECT r.Id, r.Title, r.Contents
FROM Resources r
LEFT OUTER JOIN Resources sub ON sub.ParentIds @> ARRAY[r.Id]::integer[]

有人能创建一个最小工作示例或指向相关文档吗?也许gorp不是这个任务的合适工具?如果有更好的替代方案,我也愿意听取建议。谢谢。

英文:

In a hobby project of mine, I have a struct like this:

type Resource struct {
    Id int
    ParentIds []int
    Title string
    Contents []byte
    Resources []Resource
}

Each resource possibly has some sub-resources ([]Resource). I'd like to get started by using a query-to-struct mapper like gorp, but I don't know how I can map a query like

SELECT r.Id, r.Title, r.Contents
FROM Resources r
LEFT OUTER JOIN Resources sub ON sub.ParentIds @> ARRAY[r.Id]::integer[]

Can anyone create a minimal working example or point me to a relevant documentation? Maybe gorp isn't the right tool for the job? If there is a better alternative, I'm also open to suggestions. Thank you.

答案1

得分: 2

在 gorp 的自述文件中有一个关于 join 的示例,链接为 https://github.com/go-gorp/gorp。我认为没有内置的方法可以像你所做的那样将不同的表放入数组中。

其中 InvoicePersonView 是一个用于保存查询结果的结构体。

// 运行你的查询
query := "select i.Id InvoiceId, p.Id PersonId, i.Memo, p.FName " +
"from invoice_test i, person_test p " +
"where i.PersonId = p.Id"

// 将一个切片传递给 Select()
var list []InvoicePersonView
_, err := dbmap.Select(&list, query)

// 这应该返回 true
expected := InvoicePersonView{inv1.Id, p1.Id, inv1.Memo, p1.FName}
if reflect.DeepEqual(list[0], expected) {
fmt.Println("Woot! My join worked!")
}

英文:

There is an example of a join in the gorp readme at https://github.com/go-gorp/gorp . I don't think there is any built-in way of putting separate tables into arrays like you are doing.

Where InvoicePersonView is a struct to hold the results of the query.

// Run your query
query := "select i.Id InvoiceId, p.Id PersonId, i.Memo, p.FName " +
    "from invoice_test i, person_test p " +
    "where i.PersonId = p.Id"

// pass a slice to Select()
var list []InvoicePersonView
_, err := dbmap.Select(&list, query)

// this should test true
expected := InvoicePersonView{inv1.Id, p1.Id, inv1.Memo, p1.FName}
if reflect.DeepEqual(list[0], expected) {
    fmt.Println("Woot! My join worked!")
}

huangapple
  • 本文由 发表于 2014年5月2日 00:48:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/23412343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定