在具有相同事务的 sequeize 中插入父/子记录的正确方法(获取父 ID)



在续集中,我们如何获取父 ID 以更新相同事务中的子记录。我正在尝试这种方式,但它无法获取父级的 ID。

db.sequelize.transaction(function (t) {
return db.Employee.create(employeeData, {transaction:t}).then(function(newEmployee)
{
//how to get the parent ID here?
var empDetailData = {x: "", y: "", emp_id:newEmployee.id};
return db.EmployeeDetails.create(empDetailData, {transaction:t}).then(function(newDetail)
{
res.json(newEmployee);
});
});
});  

数据库关系

Employee.hasMany(EmployeeDetails, {foreignKey:'emp_id'});  

它错误地说emp_id不能为空。任何正确方向的指示将不胜感激。 如何获取 ID 以便交易可以正常工作。

已解决:实际问题是数据库代码缺少自动增量:true

id: {
type:  Sequelize.INTEGER,
primaryKey: true,
**autoIncrement: true** was missing. 
},

你缺少的是t.commit()t.rollback()。你需要newEmployeenewDetails的 promise 链中,这会在 promise 回调链中引入回调地狱。下面给出了一个使用Async/Await的非常整洁的版本,并带有t.commit()t.rollback()

async function createUser(employeeData) {
let transaction;
try {
transaction = await db.sequelize.transaction();
const newEmployee = await db.Employee.create( employeeData, {
transaction: transaction
})
const empDetailData = {
x: "",
y: "",
emp_id:newEmployee.id
};
await db.EmployeeDetails.create(empDetailData, {
transaction: transaction
})
await transaction.commit()
res.json(newEmployee)
} catch(error) {
if(transaction) {
await transaction.rollback()
}
// HANDLE THE ERROR AS YOU MANAGE IN YOUR PROJECT
}
} 
createUserWithDetails = async(data) => {
try {
const transaction = await db.sequelize.transaction(async (t) => {
let newEmp = await db.Employee.create(employeeData,{transaction:t});
let empDetailData = {x: "", y: "", emp_id: newEmp.id};
let details = await db.EmployeeDetails.create(empDetailData, {transaction:t});
// If you've made it so far everything is ok and
// the transaction will be automatically committed.
res.json(newEmp);
});
return transaction;
}
catch(error) {
// Handle Error
// The transaction is automatically rollbacked!
}

最新更新