javascript - 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}' }`
我知道我必须以某种方式生成一个对象,但我不知道如何在动态替换值的同时做到这一点.....有什么建议吗?
京东
解决方案
推荐阅读
- sharepoint - Microsoft SharePoint API 访问被拒绝
- html - 网页图像在移动浏览器上显示为黑色
- android - Android:使用zxing扫描条码并返回片段中的结果
- html - 如何使用 CSS 和 HTML 隐藏高级搜索表单?
- windows - 如何在 Powershell 和 nano 下保存 git commit 消息?(Ctrl+O 不起作用)
- node.js - 将mongo从本地部署到服务器
- javascript - React - 使用 wp_mail 发送电子邮件
- java - Mockito - when ... thenReturn 通过传递期望值列表多次返回
- python-3.x - AttributeError:ResultSet 对象没有属性“get_text”。您可能将元素列表视为单个元素
- iterm2 - 如何偶尔将热键窗口固定到特定桌面