繁体   English   中英

如何在sequelize中使用事务?

[英]how to use transactions in sequelize?

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

用户 class:

'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;
};

儿童 class:

'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;
};

尝试:

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();
}


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM