我希望能够更改列表的顺序位置。每个列表都有自己的位置字段。当我更新列表顺序时,我想将其保存到数据库中。因此,我以正确的顺序传递一个包含列表 id 字段的数组,并使用中等复杂的查询来更新列表:
with pos as (
select
id as pos_id,
row_number() over() as position
from (
select unnest(
array[36, 33, 35, 37, 46, 39, 40, 41, 43, 45, 38, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 61, 62, 65, 66, 67, 68, 78, 79, 82, 83]
) as id
) a
)
update lists l
set position = pos.position
from
pos
where
l.id = pos.pos_id
这在 pg_admin 中工作得很好,但是当我尝试将其放入 Node 中时,它就不起作用了。
我尝试使用这些形式发送 $1 参数:
没有一个起作用。其中一些返回解析错误,一些返回“需要添加显式类型转换”错误。在这种情况下,如何将数组传递给 pool.query ?
当我尝试时,我应该犯一些错误。因为选项2, unnest($1::bigint) 工作得很好,因为我试图一一确认所有表格。
所以正确的代码是:
let positions = [36, 33, 35, 37, 46, 39, 40, 41, 43, 45, 38, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 61, 62, 65, 66, 67, 68, 78, 79, 82, 83];
pool.query('with pos as ( select id as pos_id, row_number() over() as position from ( select unnest($1::bigint[]) as id ) a ) update listas l set position = pos.position from pos where l.id = pos.pos_id',
[positions], (error) => {
... whatever