2

After some research I didn't find anything related to my problem. So the setting is an M:M relationship already working with sequelize (sqllite):

return User.find({ where: { _id: userId } }).then(user => {
   logger.info(`UserController - found user`);
   Notification.find({ where: { _id: notificationId } }).then(notification => {
      if (associate) {
        return user.addNotification([notification]);
      } else {
        return user.removeNotification([notification]);
      }
   })
})

The thing is that I have extra fields in the inter table(cityId, active) and I don't know how to update it when running "addNotification".

Thanks in advance

Bernardo
  • 531
  • 1
  • 13
  • 31

3 Answers3

8

If you are using Sequelize version 4.x there is some changes in the API

Relationships add/set/create setters now set through attributes by passing them as options.through (previously second argument was used as through attributes, now its considered options with through being a sub option)

user.addNotification(notification, { through: {cityId: 1, active: true}});
RPaul
  • 946
  • 10
  • 11
4

In order to add data to pivot table you should pass data as second parameter of add function

user.addNotification(notification, {cityId: 1, active: true});
Yrysbek Tilekbekov
  • 2,685
  • 11
  • 17
  • Just a note that API + the documentation changed since and the answer by RPaul is valid for Sequelize v4+ – jarodsmk Mar 12 '19 at 13:56
2

When the join table has additional attributes, these can be passed in the options object:

UserProject = sequelize.define('user_project', {
  role: Sequelize.STRING
});
User.belongsToMany(Project, { through: UserProject });
Project.belongsToMany(User, { through: UserProject });
// through is required!

user.addProject(project, { through: { role: 'manager' }});

You can find more about this here: https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html