I am working with Sequelize 4.38.0 and I have a problem with the belongsToMany association.
I defined my tables like this:
const Role = db.define('role', {
name: {type: Sequelize.STRING, allowNull: false},
standard: {type: Sequelize.BOOLEAN, allowNull: false}
})
const Privilege = db.define('privilege', {
id: {type: Sequelize.STRING, allowNull: false, primaryKey: true},
description: {type: Sequelize.TEXT, allowNull: false}
})
const RolePrivilege = db.define('rolePrivileges', {
restriction: {type: Sequelize.STRING, allowNull: true}
})
Privilege.belongsToMany(Role, {through: RolePrivilege})
Role.belongsToMany(Privilege, {through: RolePrivilege})
So the code says that a privilege can have many roles, a role can also have many privileges - so it is a n:m association.
Like you saw above I created that association through the table RolePrivilege
which has an additional attribute restriction
.
When I want to add privileges to roles I usually do it like this:
Role.build({id: role}).setPrivileges(privileges)
where privileges
is just an array of privilege ID's.
So i now want to fill the restriction
field in the join table (RolePrivileges
) to a special value for each privilege to role association.
So I tried the following like it described here
privileges = privileges.map(p => {
const priv = Privilege.build({id: p})
priv.rolePrivileges.restriction = 'a'
return priv
})
and did the same query like above. But it throws the error that setting restriction
on undefined is not possible. After a long google session I tried including the association table on the build
method, but it still did not work.
Can you help me with that?