vondip
vondip

Reputation: 14029

sequelize - how to update an association in n-m relation including join table

I have two tables (user, tag) that are connected to each other with a belongsToMany relationship through a join entity (user_tag):

sequelize.define('tag', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    type: {
      type: DataTypes.STRING
    }
  }, {
       classMethods: {
            associate: function (models) {
            this.belongsToMany(models.user, {as: "users", through: models.user_tag });
  },
  }

}

sequelize.define('user', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    name: {
      type: DataTypes.STRING,
    },{
    classMethods: {
        associate: function (models) {
         this.belongsToMany(models.tag, { as:"tags", through: models.user_tags });
        }
    }
}


sequelize.define('user_tag', {
    type: DataTypes.STRING,
    param1: DataTypes.INTEGER,
    priority: DataTypes.INTEGER
  }, {
    freezeTableName: true,
    paranoid: true
  });

Now, a user can update all his tags, including all the specific information on the join entity (user_tag) for example priority and param1.

I'm aware of setAssociation [ e.g. user.setTag(myTags) ], however, how do I set the matching param1 and priority properties?

Upvotes: 2

Views: 1940

Answers (1)

jjbskir
jjbskir

Reputation: 10597

According to Sequelize's documentation when adding a new relationship with belongsToMany, you can pass in additional attributes to the option object and that data will get added to the through model.

user.setTag(myTags, { param1: 1, priority: 1 });

Upvotes: 1

Related Questions