postgresql Sequelize.js:查询不在数组中(数组中的项目为 $ne)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43125925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sequelize.js: Query for not in array ($ne for items in array)
提问by Yo Wakita
I am looking to pull items from a postgres data base with Sequelize, but only return items that have an id that does not equal any items in a given array.
我希望使用 Sequelize 从 postgres 数据库中提取项目,但只返回 ID 不等于给定数组中任何项目的项目。
In the Sequelize documentation, there are operators $ne
for not equal
and $in
for returning items that have properties with values that match the given array, but it doesn't look like there is an operator for something that combines those two.
在Sequelize 文档中,有$ne
用于not equal
和$in
用于返回具有与给定数组匹配的值的属性的项目的运算符,但看起来没有用于组合这两者的运算符。
For example, if I were to have items in my database with ids [1, 2, 3, 4, 5, 6]
, and I wanted to filter those by comparing to another array (ie [2,3,4]
), so that it would return items [1, 5, 6]
. In my example i also randomize the return order and limit, but that can be disregarded.
例如,如果我的数据库中有 ids 的项目[1, 2, 3, 4, 5, 6]
,并且我想通过与另一个数组(即[2,3,4]
)进行比较来过滤这些项目,以便它返回 items [1, 5, 6]
。在我的示例中,我还随机化了退货单和限制,但这可以忽略不计。
function quizQuestions(req, res) {
const query = {
limit: 10,
order: [ [sequelize.fn('RANDOM')] ],
where: {
id: { $ne: [1, 2, 3] } // This does not work
}
};
Question.findAll(query)
.then(results => res.status(200).json(map(results, r => r.dataValues)))
.catch(err => res.status(500).json(err));
}
Edit: With @piotrbienias answer, my query looks like this:
编辑:使用@piotrbienias 回答,我的查询如下所示:
const query = {
limit: 10,
order: [ [sequelize.fn('RANDOM')] ],
where: {
id: { $notIn: [1, 2, 3] }
}
};
回答by Derit Agustin
回答by piotrbienias
There exists $notIn
, you must have missed it. Exemplary query with $notIn
generates
存在$notIn
,你一定错过了。带有$notIn
生成的示例查询
SELECT "id", "name"
FROM "categories" AS "Category"
WHERE "Category"."id" NOT IN (1, 2);
EDIT
编辑
The documentation you refer to is for 2.0
version of Sequelize, you should update to 3.0
.
您参考的文档是针对2.0
Sequelize 版本的,您应该更新到3.0
.