pg-promise在UPDATE SET语句中使用命名参数

问题描述 投票:0回答:1

我想用命名参数实现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)

对象字段可能根据发送的请求而有所不同,所以我不想“硬编码”其中的参数。

javascript node.js pg-promise
1个回答
0
投票

[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);
© www.soinside.com 2019 - 2024. All rights reserved.