Compare two fields in Waterline/Sails.js query

2019-08-08 02:13发布

I want to compare two fields in my Waterline query in Sails.js application, e.g.: SELECT * FROM entity E WHERE E.current < E.max.

I've tried the following code, but it's expecting integer value to be passed to it instead of column name:

Entity.find({
  where: {
    current: {'<': 'max'}
  }
});

So, how do I compare two columns?

2条回答
劳资没心,怎么记你
2楼-- · 2019-08-08 02:33

The other way would be to use one query to get the max before putting it in the criteria.

EntityOne.find({
  sort: 'column DESC'
}).limit(1)
  .exec(function(err,found){
    var max = found[0]
    EntityTwo.find({
      where: {
        current: {'<': found}
      }
    }).exec((err,found) {
      // Do stuff here
      });
  });

The query method is ultimately going to be faster however

查看更多
乱世女痞
3楼-- · 2019-08-08 02:42

I have ran some tests and at the same time read the Waterline documentation. There is no indication of anything that could possibly do comparison of two fields/columns via .find() or .where() methods. Reference: http://sailsjs.org/documentation/concepts/models-and-orm/query-language

Instead, I have used .query() method to compare two fields via SQL string such as :

Entity.query("SELECT * FROM `Entity` E WHERE E.current < E.max", function( err, res) {
  if(err) {
    //exception
  } else {
    console.log('response',res);
  }
});
查看更多
登录 后发表回答