【问题标题】:Transaction with Sequelize doesn't work与 Sequelize 的交易不起作用
【发布时间】:2015-02-27 04:46:27
【问题描述】:

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

我正在使用 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查询都生成了,所以没有任何东西插入到db中。

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

有什么想法或建议吗?

感谢您的帮助!

【问题讨论】:

  • 您的 Group 模型不应该使用 hasMany 而不是 belongsToMany
  • 有什么好处?
  • 您应该考虑在 sequelize 的问题跟踪器上打开一个问题 - 从一开始您的代码看起来应该可以工作。

标签: sql node.js transactions promise sequelize.js


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-11-02
    • 2014-05-28
    • 2011-08-19
    • 2020-03-05
    • 1970-01-01
    • 2017-12-03
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多