Search code examples
node.jsmany-to-manysequelize.js

Sequelize create transaction with include and junction table


I am trying to insert a new record that is associated to 2 other entities via junction tables. Like this:

Staff -< deploymentCrew >- Deployment -< deploymentEquipment >- Equipment

Staff And deployment tables:

module.exports = function(sequelize, Sequelize) {

  var Staff = sequelize.define('staff', {

    _id: {
      autoIncrement: true,
      primaryKey: true,
      type: Sequelize.INTEGER
    },

    _firstname: {
      type: Sequelize.STRING,
      notEmpty: true
    },

    _lastname: {
      type: Sequelize.STRING
    },

    _phonework: {
      type: Sequelize.STRING
    },

    _phonehome: {
      type: Sequelize.STRING
    },

    _img: {
      type: Sequelize.STRING
    },

    _emailpersonal: {
      type: Sequelize.STRING
    },

    _emailwork: {
      type: Sequelize.STRING
    },

    _position: {
      type: Sequelize.STRING
    },

    _notes: {
      type: Sequelize.STRING
    },

    _status: {
      type: Sequelize.STRING,
      defaultValue: 'active'
    }

  });

  return Staff;

};


module.exports = function(sequelize, Sequelize) {

  var Deployment = sequelize.define('deployment', {

    _id: {
      autoIncrement: true,
      primaryKey: true,
      type: Sequelize.INTEGER
    },

    _datedeployed: {
      type: Sequelize.DATEONLY,
      notEmpty: true
    },

    _datereturned: {
      type: Sequelize.DATEONLY
    },

    _city: {
      type: Sequelize.STRING
    },

    _province: {
      type: Sequelize.STRING
    },

    _country: {
      type: Sequelize.STRING
    },


    _unitnumber: {
      type: Sequelize.STRING
    },

    _comments: {
      type: Sequelize.TEXT
    },

    _productid: {
      type: Sequelize.INTEGER
    },

    _contractid: {
      type: Sequelize.INTEGER
    },

    _deploymenttypeid: {
      type: Sequelize.INTEGER
    },

    _finalsold: {
      type: Sequelize.NUMERIC(17,3)
    },

    _pricing: {
      type: Sequelize.TEXT,
      get: function () {
        return JSON.parse(this.getDataValue('value'));
      },
      set: function (value) {
        this.setDataValue('value', JSON.stringify(value));
      }
    },

    _status: {
      type: Sequelize.STRING,
      defaultValue: 'active'
    },

    createdBy: {
      type: Sequelize.STRING
    }

  });


  return Deployment;

};

My code for the junction tables is just like this:

  module.exports = function(sequelize, Sequelize) {

  var DeploymentEquipment = sequelize.define('deploymentEquipment', {

  });

  DeploymentEquipment.associate = function(models){
    models.equipment.belongsToMany(models.deployment, {through: models.deploymentEquipment, foreignKey: 'equipmentId'});
    models.deployment.belongsToMany(models.equipment, {through: models.deploymentEquipment, foreignKey: 'deploymentId'});
  };


  return DeploymentEquipment;

};


module.exports = function(sequelize, Sequelize) {

  var DeploymentCrew = sequelize.define('deploymentCrew', {

    _timex: {
      type: Sequelize.DATEONLY,
      notEmpty: true
    },

    _dateon: {
      type: Sequelize.DATEONLY
    },

    _dateoff: {
      type: Sequelize.DATEONLY
    },

    _role: {
      type: Sequelize.STRING
    }

  });

  DeploymentCrew.associate = function(models){
    models.staff.belongsToMany(models.deployment, {through: models.deploymentCrew, foreignKey: 'staffId'});
    models.deployment.belongsToMany(models.staff, {through: models.deploymentCrew, foreignKey: 'deploymentId'});
  };


  return DeploymentCrew;

};

That all seems to work great. But my create statement leaves out the deploymentid in the insert statement. Here is my code:

  var deployment = req.body;
  var crew = req.body._deploymentcrew;
  var equipment = req.body._deploymentequipment;

    //insert new deployment - start transaction, add deployment, get ID, loop through crew, loop through equipment
    models.sequelize.transaction(t =>{
      var promises = [];
      return models.deployment.create(req.body, {transaction: t}).then(function(newDeployment) {
        for(var i=0; i < equipment.length; i++){
          var equip = equipment[i];
          equip.deploymentid = newDeployment.id;
          equip.equipmentId = equipment[i].id;
          var newPromise = models.deploymentEquipment.create(equip, promises.push(newPromise));
        }

        for(var i=0; i < crew.length; i++){
          var staff = crew[i];
          staff.deploymentid = newDeployment.id;
          staff.staffId = crew[i].staff.id;
          var newPromise = models.deploymentCrew.create(staff, promises.push(newPromise));
        }

        return Promise.all(promises)
      });

When I look at the console, this is the insert statement:

Executing (default): INSERT INTO deploymentCrews (_timex,_dateon,_dateoff ,_role,createdAt,updatedAt,staffId) VALUES ('2018-03-01','2018-03-12',N ULL,'lead','2018-03-02 19:21:10','2018-03-02 19:21:10',5);

Notice that there is staffId, but no deploymentId. Any thoughts why? I have tried using include:[models._deploymentcrew] but am unsure of that way to do things with transactions.

Any advice would be very appreciated. Thanks!


Solution

  • While creating N:M associations, we need to specify foreignkeys of both the tables as follows

    Staff.associate = function(models){
        Staff.belongsToMany(models.deployment, {through: models.deploymentCrew, foreignKey: 'staffId'});
    };
    
    Deployment.associate = function(models) {
       Deployment.belongsToMany(models.staff, {through: models.deploymentCrew, foreignKey: 'deploymentId'});
    };
    

    Add the above to the respective table definitions and remove association in deploymentCrew