繁体   English   中英

在 where 条件下使用 " 续行包装列

[英]Sequelize wrap column with " in where condition

我在数据库中有一个 JSONB 列。

我想向 DB 提出请求,我可以在其中检查此 JSON 中的某些值是真还是假:

SELECT *
FROM table
WHERE ("json_column"->'data'->>'data2')::boolean = true AND id = '00000000-1111-2222-3333-456789abcdef'
LIMIT 1

所以,我的续集请求:

const someVariableWithColumnName = 'data2';
Model.findOne({
  where: {
    [`$("json_column"->'data'->>'${someVariableWithColumnName}')::boolean$`]: true,
    id: someIdVariable,
  },
  order: [/* some order, doesn't matter */],
})

并且 sequelize 产生不好的结果,例如:

SELECT *
FROM table
WHERE "(json_column"."->'data'->>'data2')::boolean" = true AND id = '00000000-1111-2222-3333-456789abcdef'
LIMIT 1

拆分我的专栏. 并将"添加到每个元素。

知道如何在 where 条件下摆脱将"添加到列中吗?

编辑:这是我对sequelize.literal()查询:

const someVariableWithColumnName = 'data2';
    Model.findOne({
      where: {
        [sequelize.literal(`$("json_column"->'data'->>'${someVariableWithColumnName}')::boolean$`)]: true,
        id: someIdVariable,
      },
      order: [/* some order, doesn't matter */],
    })

您可以使用Sequelize.literal()来避免虚假引号。 恕我直言,将 json 处理包装在 db 函数中也可能会有所帮助。

我刚刚遇到了一个类似的用例。

我相信您可以将静态sequelize.where方法与sequelize.literal结合使用。

这是 sequelize API 参考中的相应文档: https ://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#static-method-where 这里是一个例子(虽然我承认很难找到) 在常规文档中: https : //sequelize.org/master/manual/model-querying-basics.html#advanced-queries-with-functions--not-just-columns-

最后,对于您的特定坐姿,请尝试以下操作:

const someVariableWithColumnName = 'data2';
Model.findOne({
  where: {
[Op.and]: [
  // We provide the virtual column sql as the first argument of sequelize.where with sequelize.literal.
  // We provide the matching condition as the second argument of sequelize.where, with the usual sequelize syntax.
  sequelize.where(sequelize.literal(`$("json_column"->'data'->>'${someVariableWithColumnName}')::boolean$`), { [Op.eq]: true }),
  { id: someIdVariable }
]
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM