Pradeep Rajashekar
Pradeep Rajashekar

Reputation: 575

Sequelize - Limiting and ordering inside include

I have associated 3 tables in Sequelize. enter image description here Using findOne am trying to retrieve one room with all messages limited to 10 and with order by message_timestamp but to no avail.

models.Room.findOne({
where: {
  room_id: room_id
},
include: [ {
  model: models.Message,
  limit: 10,
  offset: 0,
  order: 'message_timestamp DESC'
} ] })

The above code retrieves all the messages (not limited to 10) and are not ordered according to message_timestamp.

Is there a solution? How can I go about doing this?

Thank You.

Upvotes: 2

Views: 4550

Answers (1)

Jake
Jake

Reputation: 1000

You cannot limit in an includes statement in sequelize. You can only limit from the top-level. With this in mind, you can try something like this:

models.Message.findAll({
  include [{
    model: models.Room,
    where: { room_id: room_id }
  }]
  limit: 10,
  offset: 0,
  order: 'message_timestamp DESC'
})

Since includes are INNER JOINs, it will only retrieve messages where the associated room_id = room_id

Upvotes: 3

Related Questions