Sequelize optional where clause parameters?

你离开我真会死。 提交于 2020-05-28 21:59:43

问题


This is one thing that really annoys me! I have to write 2 different functions for almost the same query!

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

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
      }

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'

Notice how it's outputting 0 = 1?! No idea why


回答1:


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


来源:https://stackoverflow.com/questions/36466395/sequelize-optional-where-clause-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!