Search code examples
node.jsincludesequelize.jssql-order-by

ORDER BY sequelize nodeJS


I want to get my user ordered by 'game_order'. I try a lot of possibilities but with no success (everytime the result is according to the id of user). I'm using the sequelize version: 5.21.12

This is my request:

exports.get_user_in_game = function(req, res) {
  models.user.findAll({
    attributes: ['id','username'],
    include: [
    {
      model: models.user_game,
      attributes: ['game_id','user_id','game_order','turn_to_pick'],
      where :{
        game_id : req.body.game_id
      },
      order:[
        /*[{model: models.user_game},'game_order','ASC']*/
        /*[models.user_game,'game_order','ASC']*/
        /*'game_order','ASC'*/
        ['game_order','ASC']
      ]
    }
    ]
  }).then(function(user_list) {
    res.status(200).send(user_list);
  }).catch(function(err) {
    console.log(err);
    res.status(400).end();
  });
};

What is the good way to order in a include model with sequelize?


Solution

  • Try below.

    exports.get_user_in_game = function(req, res) {
      models.user.findAll({
        attributes: ['id','username'],
        include: [
        {
          model: models.user_game,
          attributes: ['game_id','user_id','game_order','turn_to_pick'],
          where :{
            game_id : req.body.game_id
          },
        }
        ],
        order:[
            [models.user_game,'game_order','ASC'],
          ]
      }).then(function(user_list) {
        res.status(200).send(user_list);
      }).catch(function(err) {
        console.log(err);
        res.status(400).end();
      });
    };
    

    For more nested includes have look on this issue on github.