【问题标题】:Sequelize: Ordering by Nested AssociationsSequelize:按嵌套关联排序
【发布时间】:2020-01-28 14:32:19
【问题描述】:

我有 4 张桌子:

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

我正在尝试使用 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


    【解决方案1】:

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

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

    【讨论】:

    • 限价和订单对我也不起作用。 order 和 separate 也不适合我。
    【解决方案2】:

    你应该试试这个。

    在您的加入中添加 > separate:true 并包含,然后您的代码应如下所示

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 2018-07-28
      • 2021-01-11
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多