MySQL Sequelize:批量插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28258694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:18:34  来源:igfitidea点击:

Sequelize: insert in bulk

mysqlnode.jssequelize.js

提问by polkovnikov.ph

I'm using Node.js, MySQL and Sequelize. I'd like to insert some 10k rows into a table at once. The table has custom primaryKeyfield, that is being set manually. The data are downloaded from web and are overlapping.

我正在使用 Node.js、MySQL 和 Sequelize。我想一次在表中插入一些 10k 行。该表具有自定义primaryKey字段,正在手动设置。数据是从网上下载的,并且是重叠的。

I'd like to have a version of bulkCreatethat wouldn't fail if any of the rows in data have unique keys that are already present in the table. Such kind of things is done in MySQL via INSERT ... ON DUPLICATE KEY UPDATEconstruct.

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

How do I do it in Sequelize?

我如何在 Sequelize 中做到这一点?

回答by Yuri Zarubin

Pass in an options object to bulkCreate with ignoreDuplicates set to true

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

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

回答by Sean

Yuri's answer will ignore duplicates... there is an option for updateOnDuplicate:

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.

如果行键已存在(在重复键更新时)要更新的字段?(仅支持 mysql 和 mariadb)。默认情况下,所有字段都会更新。

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

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

回答by Alexander Gulakov

ProductAttribute.bulkCreate(arrayToUpsert, {updateOnDuplicate: ['id', 'attributeValue'] })- this will update each attributeValue with ids indicated in arrayToUpsert

ProductAttribute.bulkCreate(arrayToUpsert, {updateOnDuplicate: ['id', 'attributeValue'] })- 这将使用 arrayToUpsert 中指示的 id 更新每个 attributeValue

回答by Rohit Parte

Below is the correct syntax for bulk update, Tested on "sequelize": "6.0.0"

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

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

It will update all the columns specfied in updateOnDuplicate by first column values which are in dataToUpdate

它将通过 dataToUpdate 中的第一列值更新 updateOnDuplicate 中指定的所有列