繁体   English   中英

MySQL中的动态搜索查询

[英]Dynamic search query in MySQL

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

我试图做这样的事情:

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

如果用户选择所有输入字段,这将很好地工作,如果用户仅选择其中几个输入字段,而其他输入字段设置为“全部”怎么办? 如何使这项工作?

先感谢您!

这是很常见的解决方案:

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

您可以使用修改来修改查询

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM