Mohd Akram
Mohd Akram

Reputation: 83

I want to add data in four different table together using sequelize nodejs

AddEmp.create({
    location: location,
    empId: empId,
    firstName: firstName,
    lastName: lastName,
    dateOfBirth: dateOfBirth,
    gender: gender,
    maritalStatus: maritalStatus,
    contactNo: contactNo,
    residenceAddress: residenceAddress,
    emailId: emailId,
    emrContactName: emrContactName,
    emrContactDetails: emrContactDetails,
    languageKnown: languageKnown,
    proficiency: proficiency,
    areaOfInt: areaOfInt,
    bloodGroup: bloodGroup,
    photograph: photograph
})
EmpEdu.create({
    university: university,
    degree: degree,
    eduStart: eduStart,
    eduEnd: eduEnd
})
EmpPreJob.create({
    company: company,
    designation: designation,
    preJobStart: preJobStart,
    preJobEnd: preJobEnd
})
EmpCurrentJob.create({
    jobStatus: jobStatus,
    start: start,
    end: end,
    jobTitle: jobTitle,
    supervisor: supervisor
})
.then(result =>{
    res.status(201).json({message: 'emp added', userId: result.id})
})
.catch(err =>{
    if(!err.statusCode){
        err.statusCode = 500;
    }
    next(err);
});

i have four table seems like me code is not right i am trying to add all this data through one form in four different tables

AddEmp.hasOne(EmpCurrentJob);AddEmp.belongsToMany(EmpEdu,{through: EmpPreJob});

well i am joining my tables like this seems likes it is not join right and my first table dosnt take any data rest three table accepts data

Upvotes: 1

Views: 136

Answers (1)

MAS
MAS

Reputation: 736

I would create a transaction and insert data in the preferred order:

db
  .sequelize
  .transaction((t) => {
    return AddEmp.create(data, {
        transaction: t
      })
      .then((done) => {
        return EmpEdu
          .create(data, {
            transaction: t
          })
      })
      .then((done) =>  {
        return EmpPreJob
          .create(data, {
            transaction: t
          })
      })
      .then((done) => {
        return EmpCurrentJob
          .create(data, {
            transaction: t
          })
      })
  })
  .then((result) => {
    res.status(201).json({
      message: 'emp added', userId: result.id
    })
  })
  .catch((error) => {})

Upvotes: 1

Related Questions