mysql - 如何将查询字符串用于 knex?
问题描述
router.get("/stocks/symbols", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.modify(function(queryBuilder) {
if (req.query.param) {
queryBuilder.where('industry',req.query.param);
}
})
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.then((rows) => {
res.json(rows)
})
.catch((err) => {
console.log(err)
res.json({ Error: false, Message: "Error in MySQL query" })
})
})
我正在尝试制作这样的功能来使用查询字符串。目前这运行没有错误,但没有做任何事情。无论我在路线之后放置 ?industry=h 还是任何东西,它都会返回相同的数据。我遵循了一个示例,但由于某种原因它不起作用。我还缺少什么?
router.get("/stocks/symbols/:industry", function (req, res, next) {
req.db
.from("stocks")
.select("name","symbol","industry")
.where('timestamp', '=', '2020-03-24T00:00:00Z')
.where("industry", "like", `%${req.params.industry}%`)
.then((rows) => {
res.json({ Error: false, Message: "Success", Cities: rows })
})
.catch((err) => {
console.log(err)
res.json({ Error: true, Message: "Error in MySQL query" })
})
})
这做了我想做的类似工作,但它不使用查询字符串。
解决方案
您需要应用正确的查询参数 - 在您的代码中使用query.param
意味着您的 url 需要包含/stocks/symbols?param=tbd
如果您期望industry
作为查询参数,则需要将其更改为:
.modify(function(queryBuilder) {
if (req.query.industry) {
queryBuilder.where('industry',req.query.industry);
}
})
推荐阅读
- ruby - 如何使用 rbenv 在 macOS 上切换 Ruby 版本
- c# - C# 属性的概念从何而来?
- sql - SQL 选择当前月份的记录
- unicode - Teradata - 查找具有特殊占位符的行
- python - 如何创建二维数组作为 array.reshape() 方法的重写代码
- javascript - 将 javascript 字符串字节编码为 base64
- java - 图片加载缓慢——使用picaso和Firebase Android Studio Java
- javascript - 如何在原型上创建将名字和姓氏组合成全名的方法
- c# - 没有集合导航属性的实体框架一对多
- javascript - 时间到时如何调用提交按钮