Skip to content

How do I apply order to includes #4553

Description

@rbjarnason

I've been trying to use this syntax but it does not seem to work, any ideas?

    include: [
        { model: models.Image, as: 'IdeaHeaderImages', order: [['Image.updated_at','ASC']] }
    ]

From here:
https://github.com/rbjarnason/your-priorities-app/blob/master/server_api/controllers/ideas.js#L97

Activity

  1. mickhansen commented on Sep 21, 2015

    @mickhansen
    Contributor

    That syntax is not currently supported (except with separate: true which only works for hasMany atm).
    You need to use the slighter longer/sweird syntax:

    findAll({
      ...
      order: [
        [models.Image, 'updated_at', 'asc']
      ]
      ...
    });
    
  2. rbjarnason commented on Sep 22, 2015

    @rbjarnason
    Author

    Thanks for a quick reply :) Unfortunately this syntax is not working for me, it throws:

    Unhandled rejection Error: 'images' in order / group clause is not valid association
        at Object.QueryGenerator.quote (/home/robert/your-priorities-app/node_modules/sequelize/lib/dialects/abstract/query-generator.js:801:17)
    
  3. rbjarnason commented on Sep 22, 2015

    @rbjarnason
    Author

    Seems to be connected to the models.Image using an as: in the include:

    { model: models.Image, as: 'IdeaHeaderImages' }

    Using your suggested method works with other models than Image that don't use the as:

  4. mickhansen commented on Sep 22, 2015

    @mickhansen
    Contributor

    Ah yes if you have an alias on your incldue you'll need to use [{ model: models.Image, as: 'IdeaHeaderImages' }, 'updated_at', 'asc']

  5. rbjarnason commented on Sep 22, 2015

    @rbjarnason
    Author

    Thanks! That worked 👍

  6. oleiba commented on Apr 24, 2016

    @oleiba

    How would one use an aliased nested model?
    e.g. if I would want to order by an attribute from a model which is associated withmodels.Image from this example (one more nesting level).

  7. rbjarnason commented on Apr 24, 2016

    @rbjarnason
    Author

    It's easy, just add the nested chain in the inner order array, here are two levels:

        order: [
          [ models.Community, { model: models.Image, as: 'CommunityLogoImages' }, 'created_at', 'asc' ]
        ],

    Here are 3 levels:

      order: [
          [ models.PointRevision, models.User, { model: models.Image, as: 'UserProfileImages' }, 'created_at', 'asc' ]
        ],
  8. oleiba commented on Apr 24, 2016

    @oleiba

    Thanks! Worked for me!

  9. dilip489 commented on Jun 22, 2016

    @dilip489

    I am trying something like this:
    order:[ { model: this.associations['profile_status'].target}, 'updatedAt', 'DESC' ], but i am getting an error as error: NaNTypeError: Converting circular structure to JSON

  10. haroldkyle commented on Apr 21, 2017

    @haroldkyle

    @dilip489 I was having this same problem because the order property needs to be in another array. In your example:

    order: [ [ { model: this.associations['profile_status'].target}, 'updatedAt', 'DESC' ] ]
    
  11. jsina commented on Sep 3, 2017

    @jsina

    Hi there
    in my case "User" has many "MBTI Test" and I want to order results by "created_at" of "MBTI Test".
    here is my code but the order is not working.

    const where = {
        name: {
          $ne: null,
        },
        privacy: {
          $gt: 0,
        }
      };
    
      if (search) {
        where.name.$like = `%${search}%`;
      }
    
      return models.User.findAll({
        include: [{
          model: models.MBTITest,
          where: {
            result: referenceType.toUpperCase()
          },
          order: [
            [models.MBTITest, 'createdAt', 'DESC']
          ],
        }],
        where,
        limit: ~~limit || 50,
        offset: ~~offset || 0,
      });
    
  12. cbaron commented on Nov 1, 2017

    @cbaron

    @jsina, you need to do:

    order: [
            [ { model: models.MBTITest }, 'createdAt', 'DESC']
          ]
    
  13. philberg commented on Nov 21, 2017

    @philberg

    @cbaron thank you! I've been trying to chase this down for awhile now and none of the docs or tests explain how to do this correctly in v4.

  14. cbaron commented on Nov 21, 2017

    @cbaron

    Yeah, the docs are really bad.

  15. 45 remaining items

  16. bobpepers commented on Jun 10, 2022

    @bobpepers

    How do I sort Corrections model depending on the sum of LinkedAddons include ?

    await models.Corrections.findAll({
            where: {partnerId: 1},
            raw: true,
            attributes: ['id'],
            include: {
                model: models.LinkedAddons,
                attributes: ['id', [Sequelize.fn('SUM', Sequelize.col('amount')), 'totalAmount']],
            },
            group: ['corrections.id'],
            order:[[{ model: models.LinkedAddons },  'id', 'desc']]
        });

    were you able to solve this? i'm trying something simular where i want order based on the sum of an included association

  17. farzanmanafi commented on Jun 10, 2022

    @farzanmanafi
    await models.Corrections.findAll({
            where: {partnerId: 1},
            raw: true,
            attributes: ['id'],
            include: {
                model: models.LinkedAddons,
                attributes: ['id', [Sequelize.fn('SUM', Sequelize.col('amount')), 'totalAmount']],
            },
            group: ['corrections.id'],
            order: sequelize.literal('totalAmount DESC')
        });
    
  18. AnkurBansal18 commented on Jun 21, 2022

    @AnkurBansal18

    order: [
    [{ model: Image, as: "IdeaHeaderImages" }, "updated_at", "DESC"],
    ],

    try this, it worked for me.

  19. ismail-arshad-codegenio commented on Jul 22, 2022

    @ismail-arshad-codegenio

    @dilip489 I was having this same problem because the order property needs to be in another array. In your example:

    order: [ [ { model: this.associations['profile_status'].target}, 'updatedAt', 'DESC' ] ]
    

    find any solution?

  20. ashadul-mridha commented on Sep 21, 2022

    @ashadul-mridha

    if anyone still needs this as I did, using separate true you can do things like this
    its work for me at 2022

    include: { model: OtherModel, separate: true, order: [ ['createdAt', 'DESC'] ] }

  21. yogithesymbian commented on Nov 18, 2022

    @yogithesymbian

    how about direct only order in order paramter in outside of include ? looks like where query using $
    for example $table.table.column$ . its only work in where query but in order its not work to order by.
    my expectede is order by table name and column , not models name.

  22. yogithesymbian commented on Nov 18, 2022

    @yogithesymbian

    my problem is

    order: [['form_hulu_miga.dm_river_boat_hm.id', `DESC`]] // the error, TypeError: Cannot read property 'type' of undefined // i use hard code here not with variable
    
    order: [[Sequelize.literal(`form_hulu_miga.dm_river_boat_hm.id`), type]]
    order: [[Sequelize.literal('form_hulu_miga.dm_river_boat_hm.id'), type]]
    

    the output of raw query the order by not use ' , how i can put the ' in order by ?

    the above code output sql is ( unExpected )

    ORDER BY
    	form_hulu_miga.dm_river_boat_hm.id DESC // these sql output from errors
    LIMIT 0,
    

    what i expected is

    ORDER BY
    	`form_hulu_miga.dm_river_boat_hm.id` DESC // here work when i try run on mySQL
    LIMIT 0,
    
  23. yogithesymbian commented on Nov 18, 2022

    @yogithesymbian

    order: [ ['createdAt', 'DESC'] ]

    now its work by

    order: [
              [Sequelize.literal(`'form_hulu_miga.dm_river_boat_hm.id'`), type] // added ` ' ' ` 
            ]
    
    ..
    order: [[Sequelize.literal(`'${field}'`), type]]
    
  24. jhawkins11 commented on Jun 14, 2023

    @jhawkins11

    For those who are still getting an error such as 'Unknown column in order clause':
    Add subquery: false as in the top level of the options object.
    The problem being if you set a LIMIT, that value defaults to true and uses a subquery to recreate the table so your included columns are not in scope.

  25. james-skills commented on Dec 26, 2024

    @james-skills

    How can we handle the case if the top statement is findByPk instead of findAll?

    Actually,

    const entry = await Patient.findByPk(patient_id, {
    {
              model: TotalSummary,
              attributes: ['total_summary_id', 'total_summary_text'],
              order: [[col('background->informationType.order'), 'ASC']],
              include: [
                {
                  model: PatientInformationType,
                  attributes: ['name', 'order'],
                },
                {
                  model: PatientInformationType,
                  attributes: ['patient_information_type_id', 'name']
                }
              ]
            }
    
    

    I'd like to sort TotalSummary out but it remains as they are.

  26. added theissue type on Mar 9, 2025
  27. removed
    type: feature
    on Mar 9, 2025
  28. LeonxLJX commented on Sep 2, 2026

    @LeonxLJX
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docs

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions