【发布时间】:2017-05-19 10:56:31
【问题描述】:
我正在尝试使用 bookshelf.js 作为 Postgresql 的 ORM 在 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 => {
...
})
})
任何帮助将不胜感激!
【问题讨论】:
标签: javascript node.js postgresql orm bookshelf.js