I'm using sequelize (postgreSQL) in my node application. Now I'm trying to change my user roles to project based roles.
So far it looked like:
User.belongsToMany(Project, { through: 'ProjectUser' }),
User.belongsToMany(Role, { through: 'RoleUser' }),
Project.belongsToMany(User, { through: 'ProjectUser' }),
Role.belongsToMany(User, { through: 'RoleUser' })
But in this case the if I allow an action for a user than it is allowed in all projects. So my thought was to use just one join table with the three references called ProjectRoleUser.
And now I use:
User.hasMany(ProjectRoleUser),
User.belongsToMany(Project, { through: 'ProjectRoleUser' }),
User.belongsToMany(Role, { through: 'ProjectRoleUser' }),
Project.hasMany(ProjectRoleUser),
Project.belongsToMany(User, { through: 'ProjectRoleUser' }),
Role.hasMany(ProjectRoleUser),
Role.belongsToMany(User, { through: 'ProjectRoleUser' })
This works perfectly fine. So the join table looks like:
ProjectId, RoleId, UserId
1, 2, 1
1, 1, 1
2, 1, 1
2, 3, 1
1, 1, 2
2, 1, 2
Is there a nice way to request a result like:
{
"id": 1,
"username": "testuser",
"Projects": [
{
"id": 1,
"projectname": "sampleproject1",
"Roles": [
{
"id": 1,
"rolename": "Viewer"
}, {
"id": 2,
"rolename": "Author"
}
]
}, {
"id": 2,
"projectname": "second project",
"Roles": [
{
"id": 1,
"rolename": "Viewer"
}, {
"id": 3,
"rolename": "Co-Author"
}
]
}
]
}, {
...
}
Can't get my head around how to include that into one query. Any help would be nice..
EDIT:
I got now a solution which works for now. But it is not really clean. Anyone knows a easier way instead of using three includes?
User.findAll({
include: [{
model: Project,
include: [{
model: Role,
include: [{
model: ProjectRoleUser,
attributes: [],
where: { UserId: { $col: 'User.id' } }
}]
}]
}]
})