【发布时间】:2015-02-27 04:46:27
【问题描述】:
我想构建一个简单的网络表单,您可以在其中输入一个人的名字、姓氏并为这个人选择多个组(但现在只有一个)
我正在使用 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查询都生成了,所以没有任何东西插入到db中。
如果我这样说
return person.setGroups( [], {transction: t});
交易成功,但当然没有插入到 GroupsPersons 中。
有什么想法或建议吗?
感谢您的帮助!
【问题讨论】:
-
您的 Group 模型不应该使用
hasMany而不是belongsToMany? -
有什么好处?
-
您应该考虑在 sequelize 的问题跟踪器上打开一个问题 - 从一开始您的代码看起来应该可以工作。
标签: sql node.js transactions promise sequelize.js