gpt4 book ai didi

node.js - 如何在sequelize中使用group by子句获取嵌套对象

转载 作者:行者123 更新时间:2023-12-03 22:33:06 24 4
gpt4 key购买 nike

我是 Postgres 的新手,面临着“group by”的一些问题。我正在使用 Sequelize
有两个表事件和用户。
事件表由以下数据组成

[{id: 1, event_name: "event1", start_time: "5:00", end_time: "6:00", user_id: 1},
{id: 2, event_name: "event1", start_time: "5:00", end_time: "6:00", user_id: 2},
{id: 3, event_name: "event2", start_time: "7:00", end_time: "8:00", user_id: 1}]
用户表由以下数据组成
[{id:1, username: "user1", fname: "fname1"},
{id:2, username: "user2", fname: "fname2"}]
我已经设置了 hasOne 关系。通过使用“包含”,我得到如下输出
[{id: 1, event_name: "event1", start_time: "5:00", end_time: "6:00", user_id: 1, users: {id:1, username: "user1", fname: "fname1"}},
{id: 2, event_name: "event1", start_time: "5:00", end_time: "6:00", user_id: 2, users: {id:2, username: "user2", fname: "fname2"}},
{id: 3, event_name: "event2", start_time: "7:00", end_time: "8:00", user_id: 1, users: {id:1, username: "user1", fname: "fname1"}}]
但我的预期输出应该如下所示
[{event_name: "event1", start_time: "5:00", end_time: "6:00", users: [{id:1, username: "user1", fname: "fname1"},{id:2, username: "user2", fname: "fname2"}]},
{event_name: "event2", start_time: "7:00", end_time: "8:00", users: [{id:1, username: "user1", fname: "fname1"}]}]
我的想法是按“event_name”、“start_time”、“end_time”分组并获取该特定事件中的所有用户并将这些用户添加到“users”数组中
请帮我拍 Sequelize 。
谢谢你

最佳答案

每个事件只属于一个用户 - 事件 hasOne() 用户,这就是为什么它作为单个对象而不是对象数组返回的原因。如果你想获得一个数组,你要么需要编写一个自定义的 getter 方法

关于node.js - 如何在sequelize中使用group by子句获取嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64892080/

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