Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a search with conditional where parameters using Sequelize

Usually whenever I write a search query for SQL, I do something similar to this:

SELECT * FROM users u
WHERE (@username IS NULL OR u.username like '%' + @username + '%')
AND (@id IS NULL OR u.id = @id)

Basically this simulates a conditional WHERE clause. We only want to compare @searchParam to the column if @searchParam was provided.

Is there a way to replicate this using Sequelize?

EDIT: Here is my best attempt which fails:

models.user.findAll({
  where: {
    username: searchParams.username || models.sequelize.col('user.username'),
    id: searchParams.id || models.sequelize.col('user.id')
  }
})

UPDATE: I found a way to do it, but it feels like a workaround. I'm certain there has to be a more elegant way. This works, but is ugly:

models.user.findAll({
  where: [
    '(? IS NULL OR "user"."username" LIKE ?) AND (? IS NULL OR "user"."id" = ?)',
    searchParams.username,
    `%${searchParams.username}%`,
    searchParams.id,
    searchParams.id
  ]
})
like image 852
Dennis W Avatar asked Feb 14 '17 21:02

Dennis W


People also ask

How do you add a place clause in Sequelize?

For a WHERE clause with a simple condition, you can add a single property to the where object. The property name will be the column name and the property value will be the value you use to filter the query. await User. findAll({ where: { firstName: "Nathan" }, });

How do you write a query in Sequelize?

Sequelize instance comes with the query() method which you can use to run a raw query. The syntax of the method is as shown below: const [results, metadata] = await sequelize. query( "Your query here", { options } );


1 Answers

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
});
like image 159
Tilekbekov Yrysbek Avatar answered Oct 24 '22 15:10

Tilekbekov Yrysbek