简体   繁体   English

Sequelize-如何查询间接关联?

[英]Sequelize - How to query for an indirect association?

In my database I have Users. 在我的数据库中,我有用户。 A user can have many Roles. 用户可以具有许多角色。 A Role can belong to many Activities and Activities can belong to many Roles. 一个角色可以属于许多活动,而活动可以属于许多角色。 A Role being associated with an Activity means any User with that Role can perform that activity. 与活动相关联的角色意味着具有该角色的任何用户都可以执行该活动。

Using Sequelize, and given a specific activity ID, what's the best way to query to see if a User instance has at least one Role that has permission to do the activity with that ID, and then return some kind of true/false response so I know if they are authorized to perform an Activity before proceeding? 使用Sequelize并给定特定的活动ID,最好的方法是查询用户实例是否具有至少一个有权使用该ID进行活动的Role,然后返回某种true / false响应,因此我在继续之前知道他们是否有权执行活动吗?

If it were a raw query, it would probably look like this: 如果它是原始查询,则可能看起来像这样:

SELECT EXISTS(SELECT * 
                FROM "Activity_Role" 
               WHERE "ActivityId" = 'READ_FILE' 
                 AND "RoleId" = ANY(SELECT "RoleId" 
                                      FROM "User_Role" 
                                     WHERE "UserId" = '12321') 
               LIMIT 1);

Is there a way to do this without resorting to a raw query? 有没有一种方法可以不诉诸原始查询?

Try nested query with where clause 尝试使用where子句进行嵌套查询

User.findAll({
       include: [{
        model: Role,
        include : [{model : Activity, where : {id : activityID}}]
       }]
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM