Tuesday, 3 December 2019

The right way to insert a parent/child record in sequelize with the same transaction (get parent ID)

In sequelize how do we get the parent id to update the child record in the same transactions. I am trying this way but it just fails to get the ID of the parent.

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);
    });
  });
});  

DB relation

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

It errors out saying emp_id cannot be null. Any pointers in the right direction would be greatly appreciated. How can I get the id so the transaction can work.



from The right way to insert a parent/child record in sequelize with the same transaction (get parent ID)

No comments:

Post a Comment