cphill
cphill

Reputation: 5914

Sequelize Order within Query and Sub-Query

I am trying to figure out how I can use the order property to order both my sub-query and parent query. With current setup, the order clause orders the parent query, but not the sub-query. Is this possible? If so, how I can achieve it?

Here is my full query:

models.Blog.findAll({
            order: 'blog_date DESC',
            limit: 10,
            include: [
            {
                model: models.Topic,
                attributes: ['topicName'],
                required: false
            },
            {
                model: models.BlogComment,
                include: [{
                    model: models.User,
                    attributes: ['userId','firstName', 'lastName']
                }],
                required: false
            }]
        })

Produces a query:

SELECT ...
FROM (SELECT ... FROM blog LIMIT 10)
LEFT OUTER JOIN topic ...
LEFT OUTER JOIN blog_comment ...
ORDER BY blog.blog_date DESC;

I'm looking to include the following ORDER BY:

FROM (SELECT ... FROM blog ORDER BY blog.blog_date LIMIT 10)

Upvotes: 0

Views: 4804

Answers (1)

Keval
Keval

Reputation: 3326

You can use the sorder subqueries the same way, add order attribute

models.Blog.findAll({
            order: 'blog_date DESC',
            limit: 10,
            include: [
            {
                model: models.Topic,
                attributes: ['topicName'],
                required: false
            },
            {
                model: models.BlogComment,
                include: [{
                    model: models.User,
                    attributes: ['userId','firstName', 'lastName'],
                    order : 'firstName DESC'
                }],
                required: false
            }]
        })

Update:

You will need to try

order: [["blog_date","DESC"]]

rather than

order: 'blog_date DESC'

Kindly refer to the following link

Sequelize js - limit and Sorting bug

Upvotes: 1

Related Questions