sql - 与 Sequelize 的事务不起作用

标签 sql node.js transactions promise sequelize.js

我想构建一个简单的网络表单,您可以在其中输入一个人的名字、姓氏并为此人选择多个组(目前只有一个)

我正在使用node.js 和sequelize 将人员存储在MariaDB 数据库中。

Sequelize 根据定义的模型创建了表 PersonsGroupsGroupsPersons

var Sequelize = require("sequelize");
var sequelize = new Sequelize(config.database, config.username, config.password, config);

var Group = sequelize.define("Group", {
    name: {
        type: DataTypes.STRING,
        allowNull: false
    }
}

var Person = sequelize.define("Person", {
    firstName: {
        type: DataTypes.STRING,
        allowNull: false
    },
    lastName: {
      type: DataTypes.STRING,
      allowNull: false
    }
}


Person.belongsToMany(Group, {as: 'Groups'});
Group.belongsToMany(Person, {as: 'Persons'});

因为创建人员并将其分配到一个组中应该在一个步骤中以原子方式处理,所以我决定使用事务,如此处的文档所示: http://sequelize.readthedocs.org/en/latest/docs/transactions/#using-transactions-with-other-sequelize-methods

var newPerson = {
    firstName: 'Hans',
    lastName: 'Fischer'
}
var id = 3    // group

sequelize.transaction(function (t) {
    return Person.create(newPerson, {transaction: t}).then(function (person) {
        return Group.find(id, {transction: t}).then(function(group){
            if (!group) throw Error("Group not found for id: " + id);
            return person.setGroups( [group], {transction: t});
        })              

    });
}).then(function (result) {
    // Transaction has been committed
    // result is whatever the result of the promise chain returned to the transaction callback is
    console.log(result);
}).catch(function (err) {
    // Transaction has been rolled back
    // err is whatever rejected the promise chain returned to the transaction callback is
    console.error(err);
});`

但由于某种原因,成功的 function (result) {.. 和 catch 中的函数都没有被调用。但是,除了 COMMIT 之外,还生成了该事务的完整 SQL 查询,因此没有向数据库中插入任何内容。

如果我这样说 return person.setGroups([], {transction: t}); 事务成功,但当然没有插入到 GroupsPersons 中。

有什么想法或建议吗?

感谢您的帮助!

最佳答案

{transaction: t} 拼写错误,现在可以使用了

关于sql - 与 Sequelize 的事务不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27715290/

相关文章:

sql - 具有多个条件的 IIF 语句

MySQL服务器全局错误日志

java - 两个 EAR 文件,相同的 JPA entitymanager,相同的事务 => 相同的 session ?

javascript - 将 JSON 对象推送到 Mongoose 数组中

node.js - 如何在 Alpine :3. 8中安装Nodejs v13.0.1?

delphi - 如何使用 FireDAC 设置 Firebird (InterBase) 的事务锁定超时?

ms-access - MS Access (Jet) 事务、工作区

mysql获取唯一日期的总和

mysql - 如果选择结果小于 10,如何更改条件

node.js - 如何通过dialogflow发送电子邮件