首页 > 解决方案 > Sequelize:如何以编程方式计算 where 子句

问题描述

我正在使用带有 sqlite3 的 sequelize 版本 4.37.6。

我正在构建一个查询接口,它为我提供查询,然后我对其进行解析以提供 sequelize compatiblewhere子句。

作为一个简单的例子,我有这个 where 子句:

{ country: { [Op.eq]: 'Germany' } }

Op.eq只是一个例子,但我需要其他人,所以根本{ country: 'Germany'}不是一个选择)。在语法上这是正确的,但问题是我的解析器将它作为字符串返回,而 sequelize 需要一个对象。如果我将where字符串直接复制并粘贴到查询程序中,则查询都可以正常工作。它们看起来与字符串相同,但显然它们作为对象粘贴到编辑器(VS Code)中。 由于符号JSON.parse()而不起作用。[Op.eq]我尝试过使用$eq,但我也没有设法让它工作(而且它不再是推荐的方式)。

这是代码的相关部分:

function parseTerm (term) {
  const attributeList = ['country', 'province', 'city', 'location', 'label', 'rating', 'category', 'genre']
  const operatorList = ['==', '>=', '<=', '!=', 'like', 'in']
  var attribute = term.split(' ')[0].substr(1)
  var operator = term.split(' ')[1]
  var value = ''
  if (attributeList.includes(attribute) && operatorList.includes(operator)) {
    value = term.substr(attribute.length + operator.length + 3).slice(0, -1)
    var sequelizeOpr = [Op.eq]
    console.log(sequelizeOpr)
    if (operator === '==') {
      sequelizeOpr = '[Op.eq]'
    }

    let returnString = `${attribute}: { ${sequelizeOpr}: '${value}' }`

我知道我必须以某种方式生成一个对象,但我不知道如何在动态替换值的同时做到这一点.....有什么建议吗?

京东

标签: javascriptsequelize.js

解决方案


推荐阅读