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) => {
|
||||
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}.`
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ module.exports = (sequelize, DataTypes) => {
|
|||
Role.belongsToMany(models.User, {
|
||||
through: "UserRoles",
|
||||
foreignKey: 'roleId',
|
||||
otherKey: 'userId',
|
||||
as: 'users',
|
||||
});
|
||||
}
|
||||
|
|
@ -25,4 +26,4 @@ module.exports = (sequelize, DataTypes) => {
|
|||
tableName: "Roles",
|
||||
});
|
||||
return Role;
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ module.exports = (sequelize, DataTypes) => {
|
|||
User.belongsToMany(models.Role, {
|
||||
through: "UserRoles",
|
||||
foreignKey: 'userId',
|
||||
otherKey: 'roleId',
|
||||
as: 'roles',
|
||||
});
|
||||
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