【发布时间】:2020-01-28 14:32:19
【问题描述】:
我有 4 张桌子:
ChatRooms
Participants
Messages
Users
- 聊天室有很多参与者
- ChatRoom 有很多消息
- 用户有很多消息
- 用户有很多参与者
- 参与者属于用户
- 消息属于用户
我正在尝试使用 Sequelize 来查询用户,并且在 Participants 关系下,我希望它返回由 ChatRoom 订购的 10 个参与者(本质上是用户)的列表以及最新消息。基本上参与者将是最近活跃的 ChatRoms。
// My current code is:
User.findAll({
include: [
{
model: Participant,
include: [
{
model: ChatRoom,
include: [{ model: Message}]
}
],
order: [[ChatRoom, Message, 'id', 'DESC']]
}
],
})
// This is what my server is returning right now,
// but the ordering is not working:
// participantId: 2 should be on top as it has a more recent message
{
userId: 1,
name: 'Kevin',
participants: [
{
participantId: 1,
userId: 1,
chatRoomId: 1,
chatRoom:
{
chatRoomId: 1,
Messages: [{
MessageId: 1,
message: 'message1',
userId: 1
},
{
MessageId: 2,
message: 'message2',
userId: 2
}]
}
},
{
participantId: 2,
userId: 1,
chatRoomId: 2,
chatRoom:
{
chatRoomId: 2,
Messages: [{
MessageId: 3,
message: 'message3',
userId: 1
},
{
MessageId: 4,
message: 'message4',
userId: 3
}]
}
}
]
}
我不知道我想要的是否可能。重要的部分是查询返回带有最新消息的聊天室。我不必在 User 对象中执行此操作。如果需要,我可以在单独的查询中执行此操作,并且我也愿意以不同的方式设计架构。
【问题讨论】:
标签: nested sequelize.js sql-order-by