FoalTS / foal

Full-featured Node.js framework 🚀
https://foalts.org/
MIT License
1.9k stars 142 forks source link

Get All Users with given permission #637

Closed esunea closed 4 years ago

esunea commented 4 years ago

Hi ! I need to get all the users with a given permission

I've tried this

    const results = await  getRepository(Permission).find({
      where: {codeName:"permission"},
      relations:["groups"]
    })

Unfortunately the permission entity doesn't include a Group[] column

export declare class Permission {
    id: number;
    name: string;
    codeName: string;
}

so i got this error :

Relation "groups" was not found, please check if it is correct and really exist in your entity.

Would it be possible to add the Many-to-Many relation for both users and groups ?

I fear of a circular reference and i am not sure how to do that, but if it is possible, i could probably do it and make a pull request.

Best regards !

LoicPoullain commented 4 years ago

Hi @esunea

In which case do you need to get all the users with a given permission?

Here is a way to fetch them:

const codeName = 'perm2';
  const users = await getRepository(User)
    .createQueryBuilder('user')
    .innerJoin('user.userPermissions', 'userPermission')
    .innerJoin('user.groups', 'group')
    .innerJoin('group.permissions', 'groupPermission')
    .where('userPermission.codeName = :codeName', { codeName })
    .orWhere('groupPermission.codeName = :codeName', { codeName })
    .getMany();
LoicPoullain commented 4 years ago

I'm sorry, the above code does not work on some particular cases. Version 1.8 will include a proper and tested static method for this: https://github.com/FoalTS/foal/pull/682