关于UPDATE multiple rows from multiple params in nodejs/pg,我需要运行以下内容:
update portfolios p
set votes = s.votes
from unnest(array[(5, 1), (15, 1), (25, 2)]) s (votes int, id int)
where p.id = s.id
其中我的数组是$ 1,如下所示:
update portfolios p
set votes = s.votes
from unnest($1) s (votes int, id int)
where p.id = s.id
但是,我的数组最初由对象组成,如:
[{votes: 5, id: 1}, {votes: 15, id: 1}, {votes: 25, id: 2}]
我试图将其转换为:
my_array = my_array.map(function(e) { return tuple(e.votes, e.id); });
但那失败了。
我需要使用与pg和Client.query一起使用的值来更正兼容数组。
如何将我的对象数组转换为尊重javascript和postgresql的?
答案 0 :(得分:0)
您可以按原样发送JSON字符串,并让PostgreSQL处理它:
update portfolios p
set votes = s.votes
from (
select (e->>'votes')::int as votes, (e->>'id')::int as id
from (select (regexp_replace($1, '"\1"', 'g'))::jsonb as jarr) j
cross join jsonb_array_elements(jarr) e
) s
where p.id = s.id;
其中$1
为[{votes: 5, id: 1}, {votes: 15, id: 1}, {votes: 25, id: 2}]', '([a-z]+)
为字符串。
答案 1 :(得分:0)
@Ziggy传递JSON的想法可以工作,虽然理想的做法是让驱动程序适应你的阵列。这是驱动程序必须传递给Postgresql的最终查询
update portfolios p
set votes = s.votes
from (
select (a->>'votes')::int as votes, (a->>'id')::int as id
from (
select jsonb_array_elements(a) as a
from (values ('[{"votes": 5, "id": 1}, {"votes": 15, "id": 1}]'::jsonb)) s(a)
) s
) s
where p.id = s.id
要传递给驱动程序的查询:
update portfolios p
set votes = s.votes
from (
select (a->>'votes')::int as votes, (a->>'id')::int as id
from (
select jsonb_array_elements(a) as a
from (values (($1)::jsonb)) s(a)
) s
) s
where p.id = s.id
$1
参数必须用JSON.stringify
:
var a = JSON.stringify(my_array_of_objects);