javascript - 如何在 sequelize 中使用事务?

标签 javascript node.js sequelize.js

我使用 sequelize 为 MySQL 数据库编写了两个类和迁移文件。
如何使用 node.js 中的事务保存用户和他的 child ?我想创建一个类,我可以在其中将所有数据库通信封装在一个文件中,然后从我的 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;
};

child 类:
'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();
}


关于javascript - 如何在 sequelize 中使用事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61434021/

相关文章:

javascript - highcharts 堆叠柱组

javascript - 如何将变量作为 url 的一部分从 html 传递给 javascript

mysql - 使用 sequelize 在 mySql 中定义静态函数(如 Mongoose )

javascript - 如何正确编写MySQL UPDATE 查询?

javascript - 单击此图像的 map 区域时获取 img 标签 ID

javascript - 参数未使用 Volley 从 android 发送到 node.js

javascript - 文件上传缺少路径属性

node.js - 我可以将 Wix 域用于 NodeJS 应用程序吗?

node.js - 更改列名 Sequelize

javascript - 单击时克隆的元素不起作用 Javascript