簡體   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