我想构建一个简单的网络表单,您可以在其中输入一个人的名字、姓氏并为此人选择多个组(目前只有一个)
我正在使用node.js 和sequelize 将人员存储在MariaDB 数据库中。
Sequelize 根据定义的模型创建了表 Persons、Groups 和 GroupsPersons。
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/