简体   繁体   English

如何通过sequelize.js中的函数进行过滤

[英]How to filter by a function in sequelize.js

I'm trying to filter results by a function and then also order the resultset with the function column. 我正在尝试按功能过滤结果,然后使用功能列对结果集进行排序。 Here is my code so far: 到目前为止,这是我的代码:

db.trip.findAll({
  attributes: [
    [
      db.sequelize.fn('SUM', 
        db.sequelize.col('departure_time'),
        db.sequelize.col('arrival_time')),
      'summation'
    ]
  ],
  where: {
    summation: {
      gte: 500
    }
  },
  order: [['summation', 'ASC']],
  logging: console.log
}).then(function(results) {

});

The SQL that gets generated makes it hard to re-reference the alias that gets created in the attributes: 生成的SQL使得很难重新引用在属性中创建的别名:

SELECT SUM("departure_time", "arrival_time") AS "summation"
FROM "trip" AS "trip" 
WHERE "trip"."summation" >= 500 
ORDER BY "trip"."summation" ASC;

Any ideas on how to make this work without making the whole query literal? 关于如何在不使用整个查询文字的情况下实现此功能的任何想法?

I found a way by making a literal statement act as an alias. 我找到了一种使文字声明充当别名的方法。 I'm using Postgres, so I'm not sure if the quoting works in other dialects: 我使用的是Postgres,所以不确定该引用是否适用于其他方言:

var summationAlias = db.sequelize.literal('"summation"');

db.trip.findAll({
  attributes: [
    [
      db.sequelize.fn('SUM', 
        db.sequelize.col('departure_time'),
        db.sequelize.col('arrival_time')),
      'summation'
    ]
  ],
  where: db.sequelize.where(summationAlias, '>=', 500),
  order: [[summationAlias, 'ASC']],
  logging: console.log
}).then(function(results) {

});

The above code generates the following SQL: 上面的代码生成以下SQL:

SELECT SUM("departure_time", "arrival_time") AS "summation"
FROM "trip" AS "trip" 
WHERE "summation" >= 500 
ORDER BY "summation" ASC;

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

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