Sequelize.js:查询不在数组中($ne 用于数组中的项目) [英] Sequelize.js: Query for not in array ($ne for items in array)

查看:19
本文介绍了Sequelize.js:查询不在数组中($ne 用于数组中的项目)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 Sequelize 从 postgres 数据库中提取项目,但只返回 ID 不等于给定数组中任何项目的项目.

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 文档中,有操作符$ne 用于 not equal$in 用于返回具有与给定数组匹配的值的属性的项目,但看起来没有运算符结合这两者的东西.

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.

例如,如果我的数据库中有 ID 为 [1, 2, 3, 4, 5, 6] 的项目,并且我想通过与另一个数组(即 [2,3,4]),这样它就会返回项目 [1, 5, 6].在我的示例中,我还随机化了退货顺序和限制,但这可以忽略.

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.

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));
}

有了@piotrbienias 的回答,我的查询看起来像这样:

With @piotrbienias answer, my query looks like this:

  const query = {
    limit: 10,
    order: [ [sequelize.fn('RANDOM')] ],
    where: {
      id: { $notIn: [1, 2, 3] }
    }
  };

推荐答案

存在$notIn,你一定错过了.$notIn 的示例查询生成

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

SELECT "id", "name"
FROM "categories" AS "Category"
WHERE "Category"."id" NOT IN (1, 2);

编辑

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

The documentation you refer to is for 2.0 version of Sequelize, you should update to 3.0.

这篇关于Sequelize.js:查询不在数组中($ne 用于数组中的项目)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆