How to order by aggregate function in sequelize
I feel like I hit a brick wall by turning my old PHP application functionality into Node and Sequelize. I may be getting close to what an ORM can do, but just want to ask before giving up.
Imagine three tables: Video
, Task
, PublishDate
.
The application requires to Video
be able to have multiple PublishDate
and multiple Task
s. Task
will have a timeline calculated by looking at the minimum Video
PublishDate
s.
So, if a Video
has two PublishDate
of 2015-12-01
and 2015-08-15
, we will use 2015-08-15
and perform additional calculations to get the date Task
.
The problem comes when I try to get a list Task
sorted by their calculated dates.
I have tried many different approaches. This last attempt tries to use the functionsequelize.fn
models.Task.findAll({
where: {isActive: false, isCompleted: false},
include: [
{
model: models.Video,
attributes: [[sequelize.fn('min', 'video.publishDates.date'), 'dueDate']],
include: [models.PublishDate]
}
],
order: [['video', 'dueDate', 'ASC']],
limit: 50
})
I don't like that I am heading in the right direction because even without an order offer, this attempt only returns one record. However, this seems to be the closest I have been all day and I am missing the information or syntax that would make it possible.
This is my first foray into the ORM world, so I apologize if there is anything simple that I am missing. I have tried my best to research the documentation and other questions on google but no luck so far.
source to share