我正在尝试使用bookshelf.js作为Postgresql在node.js应用程序中实现基于角色的访问控制。我有以下架构:
USERS <- USERS_ROLES -> ROLES <- ROLES_RIGHTS -> RIGHTS我希望能够获得用户拥有的所有权限。在sql中,我会这样做:
SELECT rights.*
FROM rights
INNER JOIN roles_rights ON roles_rights.right_id=rights.id
INNER JOIN users_roles ON users_roles.role_id = roles_rights.role_id
WHERE users_roles.user_id=1
GROUP BY rights.id作为Bookshelf.js的新手,我在弄清楚如何建立这种关系时遇到了一些麻烦。这是我的第一次尝试:
const User = bookshelf.Model.extend({
tableName: 'users',
roles: function() {
return this.belongsToMany(Role, 'users_roles', 'user_id', 'role_id')
},
rights: function() {
return this.belongsToMany(Right, 'users_roles', 'user_id', 'role_id')
.query(qb => qb
.innerJoin('roles_rights', 'roles_rights.right_id', 'rights.id')
)
}
})
const Role = bookshelf.Model.extend({
tableName: 'roles',
rights: function() {
return this.belongsToMany(Right, 'roles_rights', 'role_id', 'right_id')
},
users: function() {
return this.belongsToMany(User, 'users_roles', 'user_id', 'role_id')
}
})
const Right = bookshelf.Model.extend({
tableName: 'rights',
roles: function() {
return this.belongsToMany(Role, 'users_roles', 'user_id', 'role_id')
}
})它不起作用。:-(
最后,我想让这个查询正常工作:
User.where({ id: req.user.get('id') })
.fetch({ withRelated: ['rights'] })
.then(user => {
...
})
})任何帮助都将不胜感激!
https://stackoverflow.com/questions/41475879
复制相似问题