续接可选的where子句参数?

Sequelize optional where clause parameters?

这是一件让我很烦恼的事情!我必须为几乎相同的查询编写 2 个不同的函数!

假设我有一个 API returns posts 与特定的 typeIdcityId 相关联。要获得与 typeId 1 OR 2, OR 3 cityId 1 关联的 ALL post,我会将以下内容解析为我的 sequelize findAll 查询:

$or: [{typeId: 1}, {typeId: 2}, {typeId: 3}]
cityId: 1

但是说我想得到所有 post 其中 cityId = 1 andOr typeId = 1,2,3,4,5,6,7,8,9,10,etc... 我不能做这样的事情:

var types = [{typeId: 1}, {typeId: 2}, {typeId: 3}]
Post.findAll({
     where: {
          if (types != []) $or: types,
          cityId: 1
      }

所以我必须创建一个不包含 $or: types where 子句的新查询...因为如果我解析一个空的 types 数组,我会得到一个奇怪的 sql 输出:

WHERE 0 = 1 AND `post`.`cityId` = '1'

注意它是如何输出 0 = 1 的吗?!不知道为什么

您可以预先构建 where 对象。这是一个简单的例子

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

我有一些类似的情况,如果字段未定义,我使用模板文字将空字符串定义为默认值。

User.findOne({
where: {
  [Op.or]: [
    { email: `${req.body.email || ""}` },
    { username: `${req.body.username || ""}` },
  ],
},

})

你可以这样做:

Post.findAll({
     where: {
          cityId: 1,
          ...(types && types.length && {
              types
          })
      }

types attr 仅在数组有元素时才在表达式中求值。