Sequelize many to many with extra columns

你。 提交于 2020-05-12 10:49:37

问题


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



来源:https://stackoverflow.com/questions/39409088/sequelize-many-to-many-with-extra-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!