我想建立一个简单的网页表单,您可以在其中输入一个人的名字、姓氏,并选择此人的多个组(但现在只能选择一个)。
我正在使用node.js和sequelize将此人存储在MariaDB数据库中。
Sequelize根据定义的模型创建了表格Persons、Groups和GroupsPersons。
但是由于某种原因,无论成功的
我正在使用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 中的函数都没有被调用。然而,整个事务的 SQL 查询语句都已经生成,除了 COMMIT,所以什么也没有插入到数据库中。如果我这样写: return person.setGroups( [], {transction: t});
事务就会成功,但是当然不会有任何插入到 GroupsPersons 的操作。有什么想法或建议吗?感谢帮助!
belongsToMany
,而应该使用hasMany
吗? - JaKXz