Sequelize many to many with extra columns

2020-08-05 10:52发布

问题:

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

回答1:

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});


回答2:

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}});


回答3:

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