You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pg-promise批量更新多行?无法获取plan_id的问题

使用pg-promise批量更新多行数据的正确方式

要实现批量更新并通过plan_id定位每行,你需要调整ColumnSet和update方法的用法,确保每个更新行都能关联到对应的plan_id:

  1. 更新ColumnSet定义:把plan_id加入列集合——虽然我们不更新这个字段,但需要它作为行匹配的条件:
const cs = new pgp.helpers.ColumnSet(
  ['plan_id', 'user_id', 'tenant_id', 'location_id', 'start_time', 'end_time', 'time_range', 'status', 'info'], 
  { table: 'workers_plan' }
);
  1. 构造批量更新语句:使用pgp.helpers.update的第三个参数指定WHERE子句模板,通过${plan_id}引用每个数据对象中的plan_id值:
const updateQuery = pgp.helpers.update(cs_values, cs, {
  where: 'plan_id = ${plan_id}'
});
  1. 执行更新:直接执行生成的查询语句即可:
await db.none(updateQuery); // db是你的pg-promise数据库实例

完整代码示例

const cs = new pgp.helpers.ColumnSet(
  ['plan_id', 'user_id', 'tenant_id', 'location_id', 'start_time', 'end_time', 'time_range', 'status', 'info'], 
  { table: 'workers_plan' }
);

const cs_values: UpdateWorkersPlan[] = plan.map((el: UpdateWorkersPlan) => ({
  plan_id: el.plan_id,
  user_id: el.user_id,
  tenant_id,
  location_id: el.location_id,
  start_time: el.start_time,
  end_time: el.end_time,
  time_range: tsrange(el.start_time, el.end_time),
  status: el.status,
  info: el.info,
}));

// 生成带WHERE条件的批量更新语句
const updateQuery = pgp.helpers.update(cs_values, cs, {
  where: 'plan_id = ${plan_id}'
});

// 执行更新
await db.none(updateQuery);

关键说明

  • pgp.helpers.update的第三个参数是配置对象,where属性接受模板字符串,其中${plan_id}会自动对应每个cs_values对象里的plan_id字段。
  • 必须把plan_id加入ColumnSet,否则模板无法引用到这个字段的值。
  • 最终生成的SQL会是批量更新语句,每行数据对应自己的plan_id匹配条件。

内容的提问来源于stack exchange,提问作者Algo771

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:57:13