【发布时间】:2014-02-24 11:15:09
【问题描述】:
是否有模型或实例方法可以执行插入或更新,具体取决于记录是否存在?最好使用 MySQL 的“INSERT ON DUPLICATE KEY UPDATE”语法?
【问题讨论】:
标签: node.js sequelize.js
是否有模型或实例方法可以执行插入或更新,具体取决于记录是否存在?最好使用 MySQL 的“INSERT ON DUPLICATE KEY UPDATE”语法?
【问题讨论】:
标签: node.js sequelize.js
现在你可以在 Sequelize 中使用upsert
【讨论】:
他们最近添加了这个功能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 目前不支持 upsert - 我认为很难引入一个好的跨方言解决方案。
但是,您可以执行 findOrCreate 和 updateAttributes。
编辑:Sequelize 现在确实支持具有相当不错的跨方言实现的 UPSERT,请参阅:https://github.com/sequelize/sequelize/pull/2518
【讨论】: