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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:32:26  来源:igfitidea点击:

Sequelize.js: Query for not in array ($ne for items in array)

postgresqlsequelize.js

提问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 $nefor not equaland $infor 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

using

使用

const Op = Sequelize.Op
where: {
      id: {[Op.notIn]:[1, 2, 3]}
}

See operators:

运营商

Sequelize exposes symbol operators that can be used for to create more complex comparisons

Sequelize 公开了可用于创建更复杂比较的符号运算符

回答by piotrbienias

There exists $notIn, you must have missed it. Exemplary query with $notIngenerates

存在$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.0version of Sequelize, you should update to 3.0.

您参考的文档是针对2.0Sequelize 版本的,您应该更新到3.0.