marko kraljevic
marko kraljevic

Reputation: 353

Sequelize sort by associated model's field

I have Chat, User and Message models, Message belongs to User and Chats can have multiple Users and User can have multiple Chats. I have working Sequelize method chat.getUsers() that returns unsorted users, and I want users sorted by createdAt of their last message in that Chat.

What I have so far is this:

     UserModel.findAll({
        include: [
          {
            model: ChatModel,
            where: { id: chat.id },
            include: [
              {
                model: MessageModel,
              },
            ],
            order: [[MessageModel, 'createdAt', 'DESC']],
          },
        ],
      });

where part filters users correctly but the order part does nothing.

Here is the complete database structure:

enter image description here

Upvotes: 0

Views: 133

Answers (1)

Jervz09
Jervz09

Reputation: 121

    [Task, 'createdAt', 'DESC'],

Source: http://sequelize.org/master/manual/querying.html

Upvotes: 1

Related Questions