我目前正試圖建立一個查詢,以便在一個jsonb陣列中尋找特定的物件。我有以下查詢,如果我使用硬編碼的字串作為 "游戲 "值,它可以正常作業。
const findGameQuery = `。
select playing
from users
where username = $1
and playing @> '[{"game": "new-pokemon-snap"}]'/span>
`
但是,如果我使用一個動態值,就像我目前對用戶名所做的那樣,我得到無效的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美元的值只是一個字串,所以不知道為什么不接受。
uj5u.com熱心網友回復:
當你發送這個查詢時,它只有一個引數:
。select playing
from users
where username = $1
and playing @> '[{"game": $2}]'/span>
正確的查詢是:
select playing
從用戶中
where username = $1
and playing @> $2
你必須用引數中的物件組成陣列。
const gameObj = [{ {
"game"/span>: game
}];
const gameParam = JSON.stringify(gameObj)。
const { rows }. = await query(findGameQuery, [username, gameParam])。
uj5u.com熱心網友回復:
你不能在一個字串字面中使用引數。
用PostgreSQL的函式構建jsonb物件:
const findGameQuery = `。
select playing
from users
where username = $1
and playing @> jsonb_build_array(jsonb_build_object('game', $2)
`
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/307791.html
標籤:
