0

我目前正在尝试构建一个查询以在 jsonb 数组中查找特定对象。如果我对“游戏”值使用硬编码字符串,我有以下查询,例如

  const findGameQuery = `
        select playing
        from users
        where username = $1
        and playing @> '[{"game": "new-pokemon-snap"}]'
    `

但是,如果我像当前对用户名一样使用动态值,则会收到无效的 json 语法错误。例如

const findGameQuery = `
        select playing
        from users
        where username = $1
        and playing @> '[{"game": $2}]'
    `

    const { rows } = await query(findGameQuery, [username, game]);
    ctx.body = rows

如何在此处使用动态值进行搜索?我进行了大量搜索,但找不到任何示例。$2 值只是一个字符串,所以不确定为什么不被接受。

4

2 回答 2

0

当您发送此查询时,它只有一个参数:

select playing
from users
where username = $1
and playing @> '[{"game": $2}]'

正确的查询是:

select playing
from users
where username = $1
and playing @> $2

您必须使用参数中的对象制作数组。

const gameObj = [{
    "game": game
}];
const gameParam = JSON.stringify(gameObj);
const { rows } = await query(findGameQuery, [username, gameParam]);
于 2021-09-14T15:01:15.063 回答
0

您不能在字符串文字中使用参数。

jsonb用 PostgreSQL 函数构造对象:

const findGameQuery = `
      select playing
      from users
      where username = $1
      and playing @> jsonb_build_array(jsonb_build_object('game', $2))
  `
于 2021-09-14T15:03:48.813 回答