[英]Pass array to function - PG and NodeJS
Using pg
in my NodeJS application I would like to be able to pass an array to a function so that I can use the IN
statement as part of my query 我想在NodeJS应用程序中使用pg
,希望能够将数组传递给函数,以便可以将IN
语句用作查询的一部分
Example 例
async function myMethod(array) {
// array looks like [ '83', '82', '54', '55', '79' ] for example
let response;
try {
response = await pool.query("SELECT * FROM fixtures WHERE id IN($1)", [array]);
} catch (e) {
console.log(e);
}
return response.rows;
}
I get an error 我得到一个错误
{ error: invalid input syntax for integer: "{"83","82","54","55","79"}"
How do I go about structuring my query here please? 我如何在这里构建查询结构?
Your best bet is to just go with: 最好的选择是:
pool.query("SELECT * FROM fixtures WHERE id IN($1:list)", [array]);
// [1,2,3]→"SELECT * FROM fixtures WHERE id IN(1,2,3)"
When a variable ends with :list
, it is formatted as a list of Comma-Separated Values, with each value formatted according to its JavaScript type. 当变量以:list
结尾时,其格式设置为逗号分隔值的列表,每个值均根据其JavaScript类型设置格式。
The reason you need that is that arrays are formatted to PostgreSQL arrays by default, which is denoted as you've seen with curly braces. 您需要这样做的原因是,默认情况下将数组格式化为PostgreSQL数组,这用大括号表示。
Note: This was added to pg
(or rather, pg-promise
), in v7.5.1. 注意:这是在v7.5.1中添加到pg
(或更确切地说是pg-promise
)的。 If you're using an earlier version, use $1:csv
instead. 如果您使用的是早期版本,请改用$1:csv
。
Source : pg-promise#csv-filter 资料来源 : pg-promise#csv-filter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.