简体   繁体   English

如何在Sequelize中按多对多关系排序?

[英]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.我通过UserCategoryUserCategory之间建立了多对多的关系,如下所示。

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?如何通过UserCategory模型中的“updatedAt”对结果进行排序

Please refer the following code to sort the result by updatedAt inside UserCategory model-请参考以下代码在UserCategory模型中按updatedAt对结果进行排序 -

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: \\ ". \\") ошибка синтаксиса (примерное положение: \\".\\")syntax error (approximate position: \\ ". \\")

First, go to Sequelize.literal() function首先,转到Sequelize.literal()函数

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特别感谢@SohamLawar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM