gpt4 book ai didi

postgresql - 去扫描 Postgres array_agg

转载 作者:行者123 更新时间:2023-12-01 21:10:48 28 4
gpt4 key购买 nike

我在 postgres 中有一对多的关系(事件有很多 EventUser),并且想扫描并存储到结构 Event .

// EventUser struct
type EventUser struct {
ID int64
CheckedIn bool
PaidAmount float32
}

// Event struct
type Event struct {
ID int64 `json:"id"`
Name string `json:"name"`
StartTime string `json:"startTime"`
EventUsers string
}

这是查询:
SELECT events.id, events.name, events."startTime", e."eventUsers" as "eventUsers"
FROM "Events" as events
LEFT JOIN (
SELECT events.id as id, array_to_json(array_agg(eu.*)) as "eventUsers"
FROM "EventUsers" as eu
JOIN "Events" AS "events" ON events.id = eu."eventId"
WHERE eu.status = 'RESERVED'
GROUP BY events.id
) AS e USING (id)
WHERE events.status = 'COMPLETED'

查询返回:
{
id: 2,
name: "2 Events are 48 days from now",
startTime: 1590471343345,
eventUsers: [
{
id: 2,
checkedIn: false,
paidAmount: 8
},
{
id: 3,
checkedIn: false,
paidAmount: 8,
},
],
};


这就是我想做的,直接扫描 eventUsers下的每一项放入结构中,并存储在 Event的结构。
got := []Event{}

for rows.Next() {
var r Event
err = rows.Scan(&r.ID, &r.Name, &r.StartTime, &r.EventUsers)
if err != nil {
panic(err)
}
}

我想我可以通过将数组存储为字符串然后 unmarshal 来实现这一点它。

我想要的是类似于 sql.NullString .

最佳答案

你可以定义一个 slice 类型来实现 sql.Scanner 界面。请注意,当您将实现 Scanner 的类型的实例传递给 (*sql.Rows).Scan(*sql.Row).Scan调用,执行者的Scan方法将被自动调用。

type EventUserList []*EventUser

func (list *EventUserList) Scan(src interface{}) error {
if data, ok := src.([]byte); ok && len(data) > 0 {
if err := json.Unmarshal(data, list); err != nil {
return err
}
}
return nil
}

然后,假设 e."eventUsers"在 select 查询中是一个 json 数组,你可以像这样使用它:
// EventUser struct
type EventUser struct {
ID int64
CheckedIn bool
PaidAmount float32
}

// Event struct
type Event struct {
ID int64 `json:"id"`
Name string `json:"name"`
StartTime string `json:"startTime"`
EventUsers EventUserList `json:"eventUsers"`
}

// ...

var events []*Event
for rows.Next() {
e := new(Event)
if err := rows.Scan(&e.ID, &e.Name, &e.StartTime, &e.EventUsers); err != nil {
return err
}
events = append(events, e)
}

关于postgresql - 去扫描 Postgres array_agg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61111104/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com