最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to order by many to many relationship in Sequelize? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Feb 26, 2020 at 4:04 theNutheNu 1911 gold badge3 silver badges12 bronze badges 2
  • What is your sequelize version? – Empty Brain Commented Feb 26, 2020 at 5:26
  • "sequelize": "^5.21.3", "sequelize-cli": "^5.5.1" – theNu Commented Feb 26, 2020 at 5:55
Add a ment  | 

3 Answers 3

Reset to default 4

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!

For those who have error like this:
ошибка синтаксиса (примерное положение: \".\") or syntax error (approximate position: \ ". \")

  1. Go to Sequelize.literal() function

  2. Change the argument string from single quotes ('') to double quotes ("")

  3. 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

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']] 
});

发布评论

评论列表(0)

  1. 暂无评论