'How to order by many to many relationship in Sequelize?

I have a many to many relationship between User and Category through UserCategory as below.

let user = await User.findAll({
  where: {
    id: req.query.user
  },
  attributes: ["id", "name"],
  include: [
    {
      model: models.Category,
      as: "interests",
      attributes: ["id", "name", "nameTH", "icon"],
      through: {
        model: models.UserCategory,
        as: "user_categories",
        attributes: ["id", "userId", "categoryId", "updatedAt"]
      }
    }
  ],
  // Here, I want to order by updatedAt in user_categories
  order: [["user_categories", "updatedAt", "DESC"]] 
});

How can I order the result by "updatedAt" inside UserCategory model?



Solution 1:[1]

Please refer the following code to sort the result by updatedAt inside UserCategory model-

let user = await User.findAll({
  where: {
    id: req.query.user
  },
  attributes: ["id", "name"],
  include: [
    {
      model: models.Category,
      as: "interests",
      attributes: ["id", "name", "nameTH", "icon"],
      through: {
        model: models.UserCategory,
        as: "user_categories",
        attributes: ["id", "userId", "categoryId", "updatedAt"]
      }
    }
  ],
  // Here, I want to order by updatedAt in user_categories
  order: [[Sequelize.literal('`interests->user_categories`.`updatedAt`'), 'DESC']] 
});

I hope it helps!

Solution 2:[2]

For those who have error like this:
?????? ?????????? (????????? ?????????: \".\") or syntax error (approximate position: \ ". \")

First, go to Sequelize.literal() function

Second, change the argument string from single quotes ('') to double quotes ("")

Then, just swap backticks ( `` ) and double quotes ("")

let user = await User.findAll({
  where: {
    id: req.query.user
  },
  attributes: ["id", "name"],
  include: [
    {
      model: models.Category,
      as: "interests",
      attributes: ["id", "name", "nameTH", "icon"],
      through: {
        model: models.UserCategory,
        as: "user_categories",
        attributes: ["id", "userId", "categoryId", "updatedAt"]
      }
    }
  ],
  // Your changes here
  order: [[Sequelize.literal(`"interests->user_categories"."updatedAt"`), 'DESC']] 
  // order: [[Sequelize.literal('`interests->user_categories`.`updatedAt`'), 'DESC']] 
});

Special thanks to @SohamLawar

Solution 3:[3]

This solution is working for me with PostgreSQL. I'm able to add an order clause on the joining table.

let user = await User.findAll({
  where: {
    id: req.query.user
  },
  attributes: ["id", "name"],
  include: [
    {
      model: models.Category,
      as: "interests",
      attributes: ["id", "name", "nameTH", "icon"],
      through: {
        model: models.UserCategory,
        as: "user_categories",
        attributes: ["id", "userId", "categoryId", "updatedAt"]
      }
    }
  ],
  // Your changes here
  order: [[{model: models.Category, as: 'interests'}, {model: models.UserCategory, as: 'user_categories'}, 'updatedAt',  'DESC']] 
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Soham Lawar
Solution 2 Selim
Solution 3 Faizan Ahmad