gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:12:44 26 4
gpt4 key购买 nike

我想使用命名参数实现 UPDATE SET 语句?可能吗?

对于像这样的对象:

{
_id: 1,
name: "new_name",
password: "new_password",
subscribed: true,
email: "new_email@email.com"
}

这是我的猜测:

UPDATE
accounts
SET
$(this:name) = $(this:csv)
WHERE
_id = $(this._id)

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

最佳答案

pg-promise 中自动执行 SET 操作的唯一方法是,如果您开始使用多行更新方法,即 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);

关于javascript - pg-promise 在 UPDATE SET 语句中使用命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59517417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com