Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 348
theNu Avatar asked Feb 26 '20 04:02

theNu


Video Answer


2 Answers

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!

like image 154
Soham Lawar Avatar answered Oct 01 '22 14:10

Soham Lawar


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

like image 38
Selim Avatar answered Oct 01 '22 16:10

Selim