如何使用 Sequelize 使用条件 where 参数执行搜索 [英] How to perform a search with conditional where parameters using Sequelize

查看:16
本文介绍了如何使用 Sequelize 使用条件 where 参数执行搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常每当我为 SQL 编写搜索查询时,我都会做类似的事情:

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)

基本上这模拟了一个有条件的 WHERE 子句.如果提供了@searchParam,我们只想将@searchParam 与列进行比较.

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

有没有办法使用 Sequelize 复制这个?

Is there a way to replicate this using Sequelize?

这是我失败的最佳尝试:

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

推荐答案

您可以只准备具有所需条件的对象.简单易懂

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

这篇关于如何使用 Sequelize 使用条件 where 参数执行搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆