序列化:按嵌套关联排序

时间:2019-05-24 11:35:57

标签: nested sequelize.js sql-order-by

我有4张桌子:

ChatRooms
Participants
Messages
Users
  1. 聊天室有很多参与者
  2. 聊天室有很多消息
  3. 用户有很多消息
  4. 用户有很多参与者
  5. 参与者属于用户
  6. 消息属于用户

我正在尝试使用Sequelize来查询用户,并且在“参与者”关系下,我希望它返回由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
                }]
            }
        }
    ]
}

我不知道自己想要什么。重要的是查询将返回带有最新消息的ChatRooms。我不必在User对象中执行此操作。如果需要,我可以在单独的查询中进行操作,而且我也乐于以其他方式设计模式。

2 个答案:

答案 0 :(得分:0)

我发现我发布的代码确实有效。问题是,当我使用limit(为简单起见而省略)时,它将执行子查询并导致其出现“找不到列”错误。

我尝试了subQuery: false,但仍然不允许我将限制与订单结合起来。

答案 1 :(得分:0)

在这里您应该尝试一下。

添加> separate:true 并加入包含,之后代码应如下所示

User.findAll({
    subQuery:false
      include: [
      {
          model: Participant,
          include: [
          {
              model: ChatRoom,
              include: [{ model: Message}],
              order: [['id', 'DESC']]
          }
          ],
        }
    ],
})