node.js-序列化OR条件obj

通过创建这样的对象

var condition=
{
  where:
  {
     LastName:"Doe",
     FirstName:["John","Jane"],
     Age:{
       gt:18
     }
  }    
}

并传递给

Student.findAll(condition)
.success(function(students){

})

它可以像这样漂亮地生成SQL

"SELECT * FROM Student WHERE LastName='Doe' AND FirstName in ("John","Jane") AND Age>18"

但是,这都是“ AND”条件,如何通过创建条件对象来生成“ OR”条件?

Morio asked 2020-01-13T07:20:58Z
6个解决方案
67 votes

似乎现在有另一种格式

where: {
    LastName: "Doe",
    $or: [
        {
            FirstName: 
            {
                $eq: "John"
            }
        }, 
        {
            FirstName: 
            {
                $eq: "Jane"
            }
        }, 
        {
            Age: 
            {
                $gt: 18
            }
        }
    ]
}

会产生

WHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)

参见文档:[http://docs.sequelizejs.com/en/latest/docs/querying/#where]

Morio answered 2020-01-13T07:21:25Z
28 votes

使用Sequelize.or

var condition = {
  where: Sequelize.and(
    { name: 'a project' },
    Sequelize.or(
      { id: [1,2,3] },
      { id: { lt: 10 } }
    )
  )
};

参考(搜寻Sequelize.or

编辑:此外,这已被修改,有关最新方法,请参见Morio的答案,

evanhadfield answered 2020-01-13T07:21:53Z
15 votes

请参阅有关查询的文档。

这将是:

$or: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)
Evan Siroky answered 2020-01-13T07:22:17Z
14 votes

基于字符串的运算符将来会被弃用(您可能已经在控制台中看到了警告)。

使它与符号运算符一起使用对我来说非常令人困惑,并且我用两个示例更新了文档。

Post.findAll({
  where: {
    [Op.or]: [{authorId: 12}, {authorId: 13}]
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Post.findAll({
  where: {
    authorId: {
      [Op.or]: [12, 13]
    }
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
CoredusK answered 2020-01-13T07:22:42Z
9 votes

对于续集4

询问

SELECT * FROM Student WHERE LastName='Doe' 
AND (FirstName = "John" or FirstName = "Jane") AND Age BETWEEN 18 AND 24 

运算符的语法

const Op = require('Sequelize').Op;

var r = await to (Student.findAll(
{
  where: {
    LastName: "Doe",
    FirstName: {
      [Op.or]: ["John", "Jane"]
    },
    Age: {
      // [Op.gt]: 18
      [Op.between]: [18, 24]
    }
  }
}
));

笔记

  • 为了获得更好的安全性,Sequelize建议删除别名运算符2700502260194494477056(例如27005022601944770770、$or ...)
  • 除非您在表模型中设置了{freezeTableName: true},否则Sequelize将针对其名称的复数形式进行查询(Student-> Students)
inmyth answered 2020-01-13T07:23:24Z
5 votes

在Sequelize版本5中,您也可以使用这种方式(充分利用Operator Sequelize):

var condition = 
{ 
  [Op.or]: [ 
   { 
     LastName: {
      [Op.eq]: "Doe"
      },
    },
   { 
     FirstName: {
      [Op.or]: ["John", "Jane"]
      }
   },
   {
      Age:{
        [Op.gt]: 18
      }
    }
 ]
}

然后,您必须包括以下内容:

const Op = require('Sequelize').Op

并传递给:

Student.findAll(condition)
.success(function(students){ 
//
})

它可以像这样漂亮地生成SQL:

"SELECT * FROM Student WHERE LastName='Doe' OR FirstName in ("John","Jane") OR Age>18"
Muhammad Fari answered 2020-01-13T07:23:57Z
translate from https://stackoverflow.com:/questions/20695062/sequelize-or-condition-object