Sequelizejs: how to use transactions along with raw queries

时间:2015-10-06 09:02:25

标签: sequelize.js

I'm using sequelize orm. I cannot find in their documentation how to use transactions when using raw queries. All I see there is for model defined query methods. But for raw queries, there is no specification on where to put the transaction object to use for that specific query.

2 个答案:

答案 0 :(得分:5)

http://docs.sequelizejs.com/en/latest/api/sequelize/#querysql-options-promise

  

[options.transaction = null]事务应在

下执行查询的事务

答案 1 :(得分:0)

上面的链接对我没有帮助,但是找到了解决方法: (如果您在catch块中回滚,则该事务将被还原。)

  sequelize.transaction(async transaction => {
    try {
      await sequelize.query(
        `
        UPDATE Balances
        SET amount = @amount := amount - ${10}
        WHERE userId=${1}`,
        {
          type: Sequelize.QueryTypes.UPDATE,
          transaction,
          raw: true
        },
      )

      await sequelize.query(
        `
        UPDATE Balances
        SET amount = @amount := amount - ${10}
        WHERE userId=${2}`,
        {
          type: Sequelize.QueryTypes.UPDATE,
          transaction,
          raw: true
        },
      )

    } catch (error) {
      transaction.rollback();
      throw `TRANSACTION_ERROR`;
    }
  })