【问题标题】:How to use query parameter as col name on sequelize query如何在 sequelize 查询中使用查询参数作为列名
【发布时间】:2018-03-04 13:27:44
【问题描述】:

所以,我有一个运行 Sequelize ORM 的 Express 服务器。客户端将使用单选按钮选项回答一些问题,并将答案作为查询参数传递给 URL,因此我可以向服务器发出 GET 请求。

问题是:我的 req.query 值应该是我的数据库表的列名。我想知道是否可以使用 Sequelize 从数据库中获取响应,并将参数作为表的列名传递。

async indexAbrigo(req, res) {
  try {
    let abrigos = null
    let type = req.query.type  // type = 'periodoTEMPORARIO'
    let reason = req.query.reason // reason = 'motivoRUA'
    abrigos = await Abrigos.findAll({
      attributes: ['idABRIGOS'],
        where: {
//I want type and reason to be the parameters that I got from client
          type: 'S',
          reason: 'S'
        }
      })
  }
  res.send(abrigos)
}

这不起作用,查询的结果类似于

(SELECT `idABRIGOS` FROM Abrigos WHERE `type` = `S` AND `reason` = `S`)

相反,我需要将该类型和原因转换为它们的值,然后将这些值传递给 SQL。有可能与Sequelize有关吗?或者甚至可以使用任何用于 Node/Express 的 ORM?

谢谢。

【问题讨论】:

    标签: sql node.js express sequelize.js


    【解决方案1】:

    谢谢 - 我正在从 req.body 传递参数,这对我来说非常有效,所以我发布它以防它可以节省某人的时间。

    app.post('/doFind', (req, res) => {
        Abrigos.findAll(
          {[req.body.field]: req.body.newVal},
          {returning: true, where: {id: req.body.id}}
        )
        .then( () => {
          res.status(200).end()
        })
        .catch(err => {
          console.log("Err: " + err)
          res.status(404).send('Error attempting to update database').end()
        })
    })
    

    【讨论】:

      【解决方案2】:

      是的,您可以使用computed property names 来完成。它看起来像这样:

      where: {
        [type]: 'S',
        [reason]: 'S'
      }
      

      您的 node.js 版本必须与 ES6 兼容。

      【讨论】:

      • 非常感谢,帮了大忙!我正在使用 ES6,现在对其进行了测试,我得到了我需要的东西。
      猜你喜欢
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 2017-10-21
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 2019-11-09
      相关资源
      最近更新 更多