【问题标题】:Pass in an array of values to update multiple rows via one raw query通过一个原始查询传入一组值以更新多行
【发布时间】:2019-02-25 06:33:32
【问题描述】:

我正在使用带有 sequelize 的原始查询来更新我的 postgres 数据库中的一个查询的多行。例如:

update customers_table as c set
    name = c2.name
from (values
    (66, 'Joe'),
    (70, 'Ann')
) as c2(id, name)
where c2.id = c.id;

在此示例中,ID 为 6670 的两行将更新其名称。

但是如何通过 sequelizejs 原始查询将要更新的数据作为 nodejs 中的数组传递?例如(这行不通,但我正在尝试了解我正在尝试做的事情):

const arrayOfData = [[66, 'Joe'], [70, 'Ann']];

const query = 
`update customers_table as c set
    name = c2.name
from (values
    ${arrayOfData}
) as c2(id, name)
where c2.id = c.id;`;

const update = sequelize.query(query).spread((results, metadata) => {
    return results;
});

【问题讨论】:

  • 还有一件事:你的arrayOfData 格式不应该是这样的:const arrayOfData = [[66, 'Joe'], [70, 'Ann']];

标签: sql node.js postgresql sequelize.js


【解决方案1】:

如果arrayOfData 中的元素个数不变,则可以使用以下语法:

db.query('update customers_table as c set
    name = c2.name
from (values
    (?),(?)
) as c2(id, name)
where c2.id = c.id', { replacements: arrayOfData })

否则,您可以简单地使用以下sn-p:

const values = arrayOfData.map(row =>  `(${row.join(',')})`).join(',')
db.query(`update customers_table as c set
    name = c2.name
from (values
    ${values}
) as c2(id, name)
where c2.id = c.id`)

您可以通过其official documentation 了解更多关于 Sequelize 原始查询的信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多