英文:
sqlx in golang - Is it possible to map joined tables?
问题
你可以在使用sqlx的情况下如何使用struct scan来处理表连接呢?
例如,假设Person有多个Post,我想要获取一个结构体,其中包含一个人的帖子作为嵌入的切片。
我想象中的DTO如下所示:
type Person struct {
Id string `json:"id"`
Name string `json:"name"`
Posts []*Post `json:"posts"`
}
type Post struct {
Id string `json:"post_id"`
}
我想使用的SQL语句如下:
SELECT
psn.id,
psn.name,
pst.id AS post_id
FROM
person psn
JOIN posts pst ON pst.person_id = psn.id
在sqlx中是否可以实现这个功能?如何实现?
英文:
How can I use sqlx struct scan in situations where I am joining tables?
For example, lets say that Person has many Post and I want to get a struct that has a persons posts embedded into it as a slice.
I am imagining a DTO like this:
type Person struct {
Id string `json:"id"`
Name string `json:"name"`
Posts []*Post `json:"posts"`
}
type Post struct {
Id string `json:"post_id"`
}
The SQL I imagine to use would be
SELECT
psn.id,
psn.name,
pst.id AS post_id
FROM
person psn
JOIN posts pst ON pst.person_id = psn.id
Is this accomplishable in sqlx? How?
答案1
得分: 1
这在sqlx中可以实现吗?如何实现?
这不是sqlx的一个功能,它不是一个ORM。它只是一个方便的包装器,其中包括使将多行选择到扁平结构体中更容易的功能。
你要么需要自己处理每个用户的多行数据,要么进行两个查询,首先查询用户信息,然后查询他们的帖子。
英文:
> Is this accomplishable in sqlx? How?
That's not a feature sqlx has, it isn't an ORM. It's just a convenience wrapper that among other things makes selecting rows into flat structs easier.
You'd either need to process the multiple rows per user yourself, or do two queries, first for the person and then for their posts.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论