我想用命名参数实现UPDATE SET语句?有可能吗?
对于像这样的对象:
{
_id: 1,
name: "new_name",
password: "new_password",
subscribed: true,
email: "[email protected]"
}
这是我的猜测:
UPDATE
accounts
SET
$(this:name) = $(this:csv)
WHERE
_id = $(this._id)
对象字段可能根据发送的请求而有所不同,所以我不想“硬编码”其中的参数。
[SET
中自动执行pg-promise
操作的唯一方法是,如果您开始使用带有ColumnSet -s的多行更新方法。
// create column set statically, once:
const cs = new pgp.helpers.ColumnSet(['?_id', 'name', 'password', 'subscribed', 'email'],
{table: 'accounts'});
生成更新查询时...
const where = pgp.as.format('WHERE _id = $1', [_id]);
const update = `${pgp.helpers.update(data, cs)} ${where}`;
执行查询:
await db.none(update);