Is there a Model or Instance method that will perform an insert or update, depending on the whether or not the record exists? Preferably making use of MySQL's "INSERT ON DUPLICATE KEY UPDATE" syntax?
INSERT ... ON DUPLICATE KEY UPDATE is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE. The row/s affected value is reported as 1 if a row is inserted, and 2 if a row is updated, unless the API's CLIENT_FOUND_ROWS flag is set.
The create() method is used to insert a single row into your SQL table. When you need to insert multiple rows at once, you need to use the bulkCreate() method instead. Finally, you can also write and execute a raw SQL statement using the sequelize. raw() method.
While Sequelize doesn't provide a bulkUpdate() method, both update() and bulkCreate() methods allow you to update multiple rows with a single method. When you need to update multiple rows with different values, you can use the bulkCreate() method.
The upsert() method accepts an object of data with the property keys serving as the column names and the property values as the column values. The method would then return an array of two elements: The instance the Model where you call the method, returning the new/updated row.
they have recently added this feature upsert
or insertOrUpdate
/**
* Insert or update a single row. An update will be executed if a row
* which matches the supplied values on either the primary key or a unique
* key is found. Note that the unique index must be defined in your sequelize
* model and not just in the table. Otherwise you may experience a unique
* constraint violation, because sequelize fails to identify the row that
* should be updated.
*/
Model.upsert({uniqueKey: 1234, name: 'joe'}).then(function () {
// cheer for joy
});
Sequelize does not currently support upsert - I believe it was hard to introduce a good cross dialect solution.
You can however do a findOrCreate and a updateAttributes.
Edit: Sequelize does now support UPSERT with a pretty decent cross dialect implementation, see: https://github.com/sequelize/sequelize/pull/2518
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With