我有一个 Object
将列名称映射到值。要更新的列事先未知,在运行时决定。
例如map = {col1: "value1", col2: "value2"}
。
我想执行一个 UPDATE
查询,将包含这些列的表更新为相应的值。我可以执行以下操作吗?如果没有,是否有一种无需手动构建查询的优雅方法?
db.none('UPDATE mytable SET $1 WHERE id = 99', map)
最佳答案
is there an elegant way of doing it without building the query manually?
是的,通过使用 helpers用于 SQL 生成。
你可以像这样预先声明一个静态对象:
const cs = new pgp.helpers.ColumnSet(['col1', 'col2'], {table: 'mytable'});
然后像这样使用它,通过 helpers.update :
const sql = pgp.helpers.update(data, cs) + /* WHERE clause with the condition */;
// and then execute it:
db.none(sql).then(data => {}).catch(error => {})
此方法适用于单个对象和对象数组,您只需相应地附加更新条件即可。
另请参阅:PostgreSQL multi-row updates in Node.js
What if the column names are not known beforehand?
请参阅:Dynamic named parameters in pg-promise ,并注意正确的答案取决于您打算如何转换此类列的类型。
关于node.js - 使用对象更新准备好的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47306155/