SequelizebulkCreate updateOnDuplicate 仅更新选定的列

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

我在这里想要实现的是,我有一个包含 N 列的表 ProfileMasters,但是其中只有 5-6 列经常更新,我们想要批量更新这些数据,实际上我们不想插入如果表中没有

id
匹配(无法找到解决方案)

因此我想出了以下声明

await ProfileMaster.bulkCreate(itemsForMaster, {updateOnDuplicate: ['id']})

这里的问题是

itemsForMaster
仅发送我们需要更新的 5-6 列,包括 id。

生成的查询如下

INSERT INTO `ProfileMasters` (`id`, `type`, `alias`, `reference`, `also_known_as`, `createdAt`, `updatedAt`)
        VALUES(3, 'profile', 'Liver Profile, LFT, liver test', '', '', '2022-09-21 05:37:48', '2022-09-21 05:37:48') ON DUPLICATE KEY UPDATE `id` = VALUES(`id`);

但是这不会更新任何内容。

你能建议我在这里缺少什么吗?

mysql node.js orm sequelize.js
2个回答
1
投票

看起来你根本不需要使用

bulkCreate
,因为你不想插入新记录。不幸的是,没有像
bulkUpdate
这样的方法,并且 RDMS 通常没有批量
UPDATE
SQL 语句,这与
INSERT
不同。
因此,总而言之,您需要循环
itemsForMaster
并为每个项目调用
update

for (const item of itemsForMaster) {
  const { id, ...fieldsToUpdate } = item;
  await ProfileMaster.update(fieldsToUpdate. { id })
}

0
投票

您传递给

Array
updateOnDuplicate
是您要更新的列。所以你只要通过
id
它总是只更新
id

© www.soinside.com 2019 - 2024. All rights reserved.