Jamie Jamie - 5 months ago 284
Node.js Question

Sequelize updating nested associations

I have an instance where I have Users and Roles. I have the following:

var User = sequelize.define("Users", {
username: DataTypes.STRING,
password: DataTypes.STRING,
});

var Role = sequelize.define("Role", {
role: DataTypes.STRING
});

var UsersRole = sequelize.define("UsersRole");

User.belongsToMany(Role, {through: UsersRole});


Which creates a UsersRoles table in the DB for me with a UserId and RoleId column. This is all working fine, but now I want to be able to update a users role, I can't work out quite how to do this! I've tried the following with no luck so far:

models.Users.findAll({
where: { id: req.params.id },
include: [{ all: true }]
}).then(function(dbUser){
dbUser[0].Roles[0].updateAttributes({
RoleId: req.body.role,
},
{
where: { UserId : req.params.id }
}
).then(function (result) {...


In summary, all I want to do is be able to change a users role, so update the 'UsersRoles' table and change the RoleId for a given UserId. I can't quite seem to figure out how to get to the UsersRoles table via any sequelize syntax!

I could write some raw SQL but that doesn't feel right?

EDIT

I just want to update a users role, if the table has:

| UserId | RoleId |
-------------------
| 1 | 1 |


I would like to be able to change it to:

| UserId | RoleId |
-------------------
| 1 | 2 |


but I can't quite figure out the code to do this!

Answer

There is no need to interact with the join table directly - You can simply do

user.setRoles([newRole]);

http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/#setassociationsnewassociations-options-promise

Notice that I'm passing an array, since users can have many roles - set removes all currently assigned roles. If you want to add a new role and keep the existing, use

user.addRole(newRole);