【问题标题】:Dynamic search query in MySQLMySQL中的动态搜索查询
【发布时间】:2017-07-10 07:09:20
【问题描述】:

这里是项目安装:
1. Nodejs服务端环境
2. MySQL 数据库(带有 Knexjs 查询生成器)
3. 数据库中的'locations' 表,其中包含'country', 'city', 'category', 'working_hours' 等字段。
4.表单输入,用户可以选择所有这些值并提交搜索。当用户什么都不选择时,它默认为“ALL”。我需要过滤数据库并选择与用户搜索输入对应的行。

我试图做这样的事情:

knex('locations').where({
   country: countryInput,
   city: cityInput,
   category: categoryInput,
   working_hours: hoursInput
   })
   .then(function(rows) {.....})
   .catch(function(err) {.....});

如果用户选择了所有输入字段,这很有效,如果用户只选择其中几个并且其他设置为“全部”怎么办?如何使这项工作?

提前谢谢你!

【问题讨论】:

标签: php mysql node.js database knex.js


【解决方案1】:

这是很常见的解决方案:

let query = knex('locations');

if (countryInput) {
  query = query.where('country', countryInput);
}

if (cityInput) {
  query = query.where('city', cityInput);
}

if (categoryInput) {
  query = query.where('category', categoryInput);
}

if (hoursInput) {
  query = query.where('working_hours', hoursInput);
}

query
  .then(function(rows) {.....})
  .catch(function(err) {.....});

【讨论】:

  • 谢谢!这正是我想要的!
【解决方案2】:

您可以使用Modify修改您的查询

期望 req.query 对象与您的 table 列匹配-

knex('locations')
        .modify(function(queryBuilder) {
            if (req.query) {
                queryBuilder.where(req.query);
            }
        }) 
   .then(function(rows) {.....})
   .catch(function(err) {.....});

嗯,有一些潜在的风险。您需要先过滤您的查询。

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 2014-10-04
    • 1970-01-01
    • 2013-11-09
    • 2014-11-25
    • 2012-11-12
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多