Cody February 2016

How to set params in join table via setAssociation options in sequelize?

I've defined the schema of table by the name labels_association, which associated labels and model X as follows:

'use strict';

module.exports = {
  up: function(queryInterface, Sequelize) {
    return queryInterface.createTable('labels_association', {
      labelId: {
        allowNull: false,
        type: Sequelize.INTEGER
      },
      associationId: {
        allowNull: false,
        type: Sequelize.INTEGER
      },
      associationType: {
        allowNull: false,
        type: Sequelize.ENUM('x', 'y')
      }
    });
  },
  down: function(queryInterface) {
    return queryInterface.dropTable('labels_association');
  }
};

Defining the has and belongs to many relationship of model X with labels via labels_association table

X.belongsToMany(Label, {
  as: 'labels',
  through: {
    model: 'labels_association',
    attributes: ['associationId', 'associationType'],
    scope: {
      associationType: 'x'
    }
  },
  foreignKey: 'associationId',
  otherKey: 'labelId'
});

Though at the time of setting labels for instance of model X, I am not able to set the associationType as 'x', while it should've already been taken care of by scope attribute in belongsToMany association.

instanceOfX.setLabels(labelIds, {
  associationType: 'x'
})

How can I set associationType with value 'x' in the above scenario?

Answers


Cody February 2016

In reference to this issue tracked on Github https://github.com/sequelize/sequelize/issues/5378

Needed to create a model for the relationship table as follows:

let LabelAssociation = sequelize.define('labelAssociation', {
  associationType: {
    type: STRING
    // etc
  }
}, {
  tableName: 'label_associations'
});

X.belongsToMany(Label, {
  as: 'labels',
  through: {
    model: LabelAssociation,
    attributes: ['associationId', 'associationType'],
    scope: {
      associationType: 'x'
    }
  },
  foreignKey: 'associationId',
  otherKey: 'labelId'
});

Explanation is as follows:

The string argument(through.model in belongsToMany options) is specifically to define a table name for an autogenerated model. If you haven't defined a model for the join model, you need to yes, otherwise Sequelize doesnt know that these extra attributes exist.

Post Status

Asked in February 2016
Viewed 1,044 times
Voted 9
Answered 1 times

Search




Leave an answer