fixed user, role and user-role association
This commit is contained in:
parent
5f1f3772ca
commit
3b65842697
|
|
@ -21,10 +21,14 @@ exports.findAll = (req, res) => {
|
||||||
exports.findOne = (req, res) => {
|
exports.findOne = (req, res) => {
|
||||||
const id = req.params.id;
|
const id = req.params.id;
|
||||||
|
|
||||||
User.findByPk(id)
|
User.findByPk(id, {
|
||||||
|
include: ['roles']
|
||||||
|
})
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (data) {
|
if (data) {
|
||||||
res.send(data);
|
let dts = data.toJSON();
|
||||||
|
dts.roles = data.roles.map(role => "ROLE_" + role.name.toUpperCase());
|
||||||
|
res.send(dts);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).send({
|
res.status(404).send({
|
||||||
message: `Cannot find user with id=${id}.`
|
message: `Cannot find user with id=${id}.`
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ module.exports = (sequelize, DataTypes) => {
|
||||||
Role.belongsToMany(models.User, {
|
Role.belongsToMany(models.User, {
|
||||||
through: "UserRoles",
|
through: "UserRoles",
|
||||||
foreignKey: 'roleId',
|
foreignKey: 'roleId',
|
||||||
|
otherKey: 'userId',
|
||||||
as: 'users',
|
as: 'users',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -25,4 +26,4 @@ module.exports = (sequelize, DataTypes) => {
|
||||||
tableName: "Roles",
|
tableName: "Roles",
|
||||||
});
|
});
|
||||||
return Role;
|
return Role;
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ module.exports = (sequelize, DataTypes) => {
|
||||||
User.belongsToMany(models.Role, {
|
User.belongsToMany(models.Role, {
|
||||||
through: "UserRoles",
|
through: "UserRoles",
|
||||||
foreignKey: 'userId',
|
foreignKey: 'userId',
|
||||||
|
otherKey: 'roleId',
|
||||||
as: 'roles',
|
as: 'roles',
|
||||||
});
|
});
|
||||||
User.belongsTo(models.Auth, {
|
User.belongsTo(models.Auth, {
|
||||||
|
|
|
||||||
|
|
@ -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;
|
||||||
|
};
|
||||||
Loading…
Reference in New Issue