我希望使用 Sequelize 从 postgres 数据库中提取项目,但只返回 ID 不等于给定数组中任何项目的项目。
在Sequelize documentation ,有运算符 $ne
用于 not equal
和 $in
用于返回具有与给定数组匹配的属性值的项目,但它不看起来好像有一个运算符可以将这两者结合起来。
例如,如果我的数据库中有 ID 为 [1, 2, 3, 4, 5, 6]
的项目,我想通过与另一个数组 (即 [2,3,4]
),这样它将返回项目 [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));
}
编辑:使用@piotrbienias 回答,我的查询如下所示:
const query = {
limit: 10,
order: [ [sequelize.fn('RANDOM')] ],
where: {
id: { $notIn: [1, 2, 3] }
}
};
最佳答案
使用
const Op = Sequelize.Op
where: {
id: {[Op.notIn]:[1, 2, 3]}
}
参见 operators :
Sequelize exposes symbol operators that can be used for to create more complex comparisons
关于postgresql - Sequelize.js:查询不在数组中(数组中的项目为 $ne),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43125925/