Sequelize:批量插入

Sequelize: insert in bulk

我正在使用 Node.js、MySQL 和 Sequelize。我想一次将大约 10k 行插入到 table 中。 table 有自定义的 primaryKey 字段,这是手动设置的。数据是从网上下载的,有重叠。

我想要一个 bulkCreate 版本,如果数据中的任何行具有已经存在于 table 中的唯一键,它也不会失败。这种事情是在 MySQL 中通过 INSERT ... ON DUPLICATE KEY UPDATE 构造完成的。

我如何在 Sequelize 中执行此操作?

将选项对象传递给 bulkCreate,并将 ignoreDuplicates 设置为 true

bulkCreate([...], { ignoreDuplicates: true })

Yuri 的回答将忽略重复项...updateOnDuplicate 有一个选项:

Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated.

http://docs.sequelizejs.com/en/latest/api/model/#bulkcreaterecords-options-promisearrayinstance

ProductAttribute.bulkCreate(arrayToUpsert, {updateOnDuplicate: ['id', 'attributeValue'] }) - 这将使用 arrayToUpsert

中指示的 id 更新每个 attributeValue

以下是批量更新的正确语法,已在 "sequelize" 上测试:“6.0.0”

model.bulkCreate(dataToUpdate, { updateOnDuplicate: ["user_id", "token", "created_at"] })

它将通过 dataToUpdate

中的第一列值更新 updateOnDuplicate 中指定的所有列