首页 > 解决方案 > 如何在sequelize中使用事务?

问题描述

我使用 sequelize 为 MySQL 数据库编写了两个类和迁移文件。如何使用 node.js 中的事务保存用户和他的孩子?我想创建一个类,我可以在其中将所有数据库通信封装在一个文件中,然后从我的 CRUD 方法中调用它。

用户类:

'use strict';
module.exports = function(sequelize, DataTypes) {
  const User = sequelize.define('User', {
    id : {
        type: DataTypes.INTEGER(11),
        allowNull: false, 
        autoIncrement:true,
        primaryKey:true
    },
    firstName : {
        type: DataTypes.STRING(50),
        allowNull: false
    },
    lastName : {
        type: DataTypes.STRING(50),
        allowNull: false
    },
    dateOfBirth : {
        type: DataTypes.DATE,
        allowNull: false
    }
  });

  return User;
};

儿童班:

'use strict';
module.exports = function(sequelize, DataTypes) {
  const Children= sequelize.define('Children', {
    id : {
        type: DataTypes.INTEGER(11),
        allowNull: false, 
        autoIncrement:true,
        primaryKey:true
    },
    userId : {
        type: DataTypes.INTEGER(11),
        allowNull: true,
        references : {
            model : 'Users',
            key:'id'
        }
    },
    status : {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaulValue: false
    },
    firstName : {
        type: DataTypes.STRING(50),
        allowNull: false
    },
    lastName : {
        type: DataTypes.STRING(50),
        allowNull: false
    },
    dateOfBirth : {
        type: DataTypes.DATE,
        allowNull: false
    }
  });
  return Children;
};

标签: javascriptnode.jssequelize.js

解决方案


尝试 :

let transaction;    
try {
    // get transaction
    transaction = await sequelize.transaction();

    //save here
    User.build({
        firstName: "John"
        //other attributes
    }).save().then(newUser => {
        const id = newUser.id;
        Children.build({
                firstNames: "fsf"
                userId: id // from newly created user
                //other attributes
            })
            .save()
            .then(children => console.log("svaed"))
    }).catch(function(error) {
        // error
    });

    // commit
    await transaction.commit();

} catch (err) {
    // Rollback transaction 
    if (transaction) await transaction.rollback();
}



推荐阅读