Sequelize 可选的 where 子句参数?
这是一件让我很恼火的事情!我必须为几乎相同的查询编写 2 个不同的函数!
This is one thing that really annoys me! I have to write 2 different functions for almost the same query!
假设我有一个 API,它返回与特定 typeId
和 cityId
相关联的 posts
.获取与 typeId 1 OR 2, OR 3
and cityId 1ALL
帖子/code> 我会将以下内容解析为我的 sequelize findAll
查询:
Say I've got an API that returns posts
that are associated to a particular typeId
and cityId
. To get ALL
posts that are associated to typeId 1 OR 2, OR 3
and cityId 1
I would parse the following to my sequelize findAll
query:
$or: [{typeId: 1}, {typeId: 2}, {typeId: 3}]
cityId: 1
但是说我想要获得 cityId = 1 andOr typeId = 1,2,3,4,5,6,7,8,9,10,etc...
的所有帖子不能做这样的事情:
But say I want to get all post where cityId = 1 andOr typeId = 1,2,3,4,5,6,7,8,9,10,etc...
I cannot do something like:
var types = [{typeId: 1}, {typeId: 2}, {typeId: 3}]
Post.findAll({
where: {
if (types != []) $or: types,
cityId: 1
}
因此,我必须创建一个不包含 $or: types
where 子句的新查询...因为如果我解析一个空的 types
数组,我得到一个奇怪的 sql
输出:
So instead I have to make a new query that won't include the $or: types
where clause...Because if I parse an empty types
array I get a weird sql
output:
WHERE 0 = 1 AND `post`.`cityId` = '1'
注意它是如何输出 0 = 1 的?!不知道为什么
Notice how it's outputting 0 = 1?! No idea why
您可以预先构建 where 对象.这是一个简单的例子
You could build the where object beforehand. Here's a simple example
// Get typeIds from whatever source you have
// Here's an example
var typeIds = [1, 2, 3];
// Or you could try this to build a query without typeIds
// var typeIds = [];
var whereCondition = {};
if (typeIds.length > 0) {
whereCondition['$or'] = typeIds.map(function(id) {
return {
typeId: id
};
})
};
whereCondition['cityId'] = 1;
console.log(whereCondition);
Post.findAll(whereCondition).then(function(posts) {
// The rest of your logic
});