javascript - 无法根据连接表字段对 sequelize 结果进行排序

标签 javascript mysql node.js sequelize.js

我正在使用 3 个 Sequelize 模型,如下所述:

tags:
id
tag_name

product_tags:
id
tag_id --> Foreign Key 'id' from tags
product_id --> Foreign Key 'id' from products
tag_score

products:
id
name

我想获取产品名称及其相关标签和标签分数,并按分数对它们进行排序,如下面的 SQL 查询所述。

select t.tag_name, p.name, pt.tag_score from tags t inner join product_tags pt on t.id = pt.tag_id inner join products p on pt.product_id = p.id order by pt.tag_score desc;

根据 sequelize 文档,这可以通过这样的 order 子句来完成:

order: [this.db.ProductTag, 'tag_score', 'DESC']

但是,我收到错误消息:无法找到模型“ProductTag”的有效关联

有人可以指出我在这里遗漏了什么吗?

编辑: Sequelize查询如下:

return this.db.Product.findAll({
  attributes: ['name'],
  include: [
    {
      model: this.db.Tag,
      as: 'tags',
      through: this.db.ProductTag,
      foreignKey: 'tag_id',
      otherKey: 'product_id',
      where: {
        tag_name: {
          $regexp: regexString
        }
      },
      required: true,
      include: [
        {
          model: this.db.ProductTag,
          as: 'product_tags',
          attributes: ['tag_score']
        }
      ]
    }
  ],
  order: [this.db.ProductTag, 'tag_score', 'DESC']
});

最佳答案

我想 sequelize 创建子查询,所以你需要改变你的顺序以获得 false 在这个 if:

if (
          subQuery
          && Array.isArray(order)
          && order[0]
          && !(order[0] instanceof Association)
          && !(typeof order[0] === 'function' && order[0].prototype instanceof Model)
          && !(typeof order[0].model === 'function' && order[0].model.prototype instanceof Model)
          && !(typeof order[0] === 'string' && model && model.associations !== undefined && model.associations[order[0]])
        ) {
          subQueryOrder.push(this.quote(order, model, '->'));
        }
        mainQueryOrder.push(this.quote(order, model, '->'));

或者你可以尝试使用sequelize.literal()。喜欢: 顺序:[[sequelize.literal('tag_score DESC')]]

关于javascript - 无法根据连接表字段对 sequelize 结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49694127/

相关文章:

mysql - mysql workbench外键样式的区别

MySQL 对象浏览器不存在

javascript - typescript - 从当前日期计算月份和年份

mysql - SQL Server 到 Mysql 的迁移(使用 Mysql Workbench)。如何在工作台向导的步骤中添加带有手动转义撇号的数据?

javascript - req.url.replace(/\/?(? :\? .*)?$/, '' ) Node js

javascript - 无服务器堆栈 : Maximum call stack size exceeded only in windows during npm run start

javascript - 在列表中查找带有扩展名的文件名

javascript - Javascript 中的非保留标识符

javascript - Angular JS - "Error: [$interpolate:interr] Can' t 插值 :"when using Highcharts

javascript - 如何为 p :remoteCommand ajax call? 传递动态值