首页 > 解决方案 > 如何将查询字符串用于 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" })
    })
})

这做了我想做的类似工作,但它不使用查询字符串。

标签: mysqlnode.jsexpressknex.js

解决方案


您需要应用正确的查询参数 - 在您的代码中使用query.param意味着您的 url 需要包含/stocks/symbols?param=tbd

如果您期望industry作为查询参数,则需要将其更改为:

.modify(function(queryBuilder) {
      if (req.query.industry) {
          queryBuilder.where('industry',req.query.industry);
      }
  })

推荐阅读