Sequelize是否支持在重复密钥更新时插入?

时间:2014-01-31 16:49:15

标签: node.js sequelize.js

是否存在将执行插入或更新的模型或实例方法,具体取决于记录是否存在?最好使用MySQL的“INSERT ON DUPLICATE KEY UPDATE”语法?

3 个答案:

答案 0 :(得分:19)

他们最近添加了此功能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
  });

答案 1 :(得分:8)

Sequelize目前不支持upsert - 我相信很难引入一个好的交叉方言解决方案。

但是,您可以执行findOrCreate和updateAttributes。

编辑:Sequelize现在支持UPSERT采用相当不错的交叉方言实现,请参阅:https://github.com/sequelize/sequelize/pull/2518

答案 2 :(得分:0)

现在您可以在Sequelize中使用upsert