在Golang中使用sqlx,是否可以映射连接的表格?

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

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.

huangapple
  • 本文由 发表于 2022年3月20日 22:43:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/71547747.html
匿名

发表评论

匿名网友

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

确定