【问题标题】:Does Sequelize support Insert on duplicate key update?Sequelize 是否支持在重复键更新时插入?
【发布时间】:2014-02-24 11:15:09
【问题描述】:

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

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    现在你可以在 Sequelize 中使用upsert

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        Sequelize 目前不支持 upsert - 我认为很难引入一个好的跨方言解决方案。

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

        编辑:Sequelize 现在确实支持具有相当不错的跨方言实现的 UPSERT,请参阅:https://github.com/sequelize/sequelize/pull/2518

        【讨论】:

        • 您好!我面临着类似的问题。我有一个以 id 作为主键的用户模型,它设置为自动递增。该模型还有一个唯一键,即“用户名”。我正在使用 findOrCreate 方法根据“用户名”字段创建或查找用户。如果记录不存在,我的代码会创建一条记录,但是当我尝试查找此记录时,会在“用户名”字段上引发 UniqueConstraintError (ER_DUP_ENTRY) --> SequelizeUniqueContraintError。基本上 findOrCreate 第二次尝试创建记录而不是找到它。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-02
        • 2019-10-28
        • 2016-09-17
        • 2011-08-31
        • 2022-01-03
        • 1970-01-01
        相关资源
        最近更新 更多