如何使用pg-promise批量更新多行?无法获取plan_id的问题
使用pg-promise批量更新多行数据的正确方式
要实现批量更新并通过plan_id定位每行,你需要调整ColumnSet和update方法的用法,确保每个更新行都能关联到对应的plan_id:
- 更新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' } );
- 构造批量更新语句:使用
pgp.helpers.update的第三个参数指定WHERE子句模板,通过${plan_id}引用每个数据对象中的plan_id值:
const updateQuery = pgp.helpers.update(cs_values, cs, { where: 'plan_id = ${plan_id}' });
- 执行更新:直接执行生成的查询语句即可:
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
相关产品推荐
相关产品推荐

