fixed user, role and user-role association

This commit is contained in:
Sascha Kühl 2025-05-26 15:41:31 +02:00
parent 5f1f3772ca
commit 3b65842697
4 changed files with 39 additions and 3 deletions

View File

@ -21,10 +21,14 @@ exports.findAll = (req, res) => {
exports.findOne = (req, res) => {
const id = req.params.id;
User.findByPk(id)
User.findByPk(id, {
include: ['roles']
})
.then(data => {
if (data) {
res.send(data);
let dts = data.toJSON();
dts.roles = data.roles.map(role => "ROLE_" + role.name.toUpperCase());
res.send(dts);
} else {
res.status(404).send({
message: `Cannot find user with id=${id}.`

View File

@ -10,6 +10,7 @@ module.exports = (sequelize, DataTypes) => {
Role.belongsToMany(models.User, {
through: "UserRoles",
foreignKey: 'roleId',
otherKey: 'userId',
as: 'users',
});
}

View File

@ -11,6 +11,7 @@ module.exports = (sequelize, DataTypes) => {
User.belongsToMany(models.Role, {
through: "UserRoles",
foreignKey: 'userId',
otherKey: 'roleId',
as: 'roles',
});
User.belongsTo(models.Auth, {

View File

@ -0,0 +1,30 @@
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class UserRole extends Model {
static associate(models) {}
}
UserRole.init({
userId: {
type: DataTypes.INTEGER,
references: {
model: 'Users',
key: 'id'
}
},
roleId: {
type: DataTypes.INTEGER,
references: {
model: 'Roles',
key: 'id'
}
}
}, {
sequelize,
modelName: 'UserRole',
tableName: 'UserRoles'
});
return UserRole;
};