How to perform a search with conditional where parameters using Sequelize How to perform a search with conditional where parameters using Sequelize sql sql

How to perform a search with conditional where parameters using Sequelize


You can just prepare object with needed conditions. Simple and easy to understand

var whereStatement = {};if(searchParams.id)    whereStatement.id = searchParams.id;if(searchParams.username)    whereStatement.username = {$like: '%' + searchParams.username + '%'};models.user.findAll({  where: whereStatement});


that's pretty awesome. thank you. i use your ideas like that:

app.get('/', function (req, res) {    ..    let foo = await Foo.findAll(    {        offset: parseInt(req.query.offset | 0),        limit: parseInt(req.query.limit | 10),        where: getFooConditions(req),    ...}function getFooConditions(req) {  fooConditions = {};  // Query param date  if (req.query.date) {    fooCondtions.start = {      [Op.gte]: moment(parseInt(req.query.date)).utc().startOf('day'),      [Op.lte]: moment(parseInt(req.query.date)).utc().endOf('day')    }  }  // Query param name  if (req.query.name) {    fooCondtions.name = {      [Op.like]: '%' + (req.query.name) + '%'    }  }  // Query param id  if (req.query.id) {    fooCondtions.id = {      [Op.equals]: '%' + (req.query.id) + '%'    }  }  return fooConditions;}


It'd be a little more complicated than you've outlined above. Sequelize has to have pretty explicit statements on ands and ors, and that means you have to use the $and and $or options to replicate what you're looking for. What you've done above is merely create the values in JavaScript and pass them to the database. Try the following:

models.user.findAll({                where: {                    $and: [{                        $or: [{                            username: {                                $like: '%' + searchParams.username '%'                            }                        }, {                            username: null                        }]                    }, {                        $or: [{                                id: searchParams.id                        }, {                           id: null                        }]                    }]                }            })

For more on this, and some good examples, see their documentation.