Skip to content

Update join table #9204

Closed
Closed

Description

@acanimal

I'm sorry but I was unable to find a clear response to this question neither in the doc and the net

How can I update a join table?

Given this scenario:

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

const user = ...  // some User instance
const project = ...  // some Project instance

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

What is the right way to update the previous role?

I found re-adding the same project to the user:

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

works and updates the role but.. is this the right way?

Activity

  1. sushantdhiman commented on Mar 22, 2018

    @sushantdhiman
    Contributor

    If N:M through model is having unique pair of foreign keys (default behaviour) then addProject is a good solution

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

    Otherwise directly finding that record on through table and updating it also an viable option

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions