Shovon
Shovon

Reputation: 67

Query using query builder to make an inner join and select with condition in typeORM

I am new to query builder. I need to apply a query. I did it on mysql and it's working fine. But I couldn't make where condition in the query.

This is my SQL query:

select users_roles.user_id 
from users_roles 
inner join roles on roles.id = users_roles.role_id  
where roles.role = 'ADMIN_ROLE' 
   or roles.role = 'SUPER_ADMIN_ROLE'

I tried to do this using query builder and did this without using any where condition. How can I filter according to that mysql code? Here I am adding my query builder query:

const query = this.userRoleRepository.createQueryBuilder('usersRoles');

      const users = await query
        .innerJoinAndSelect('usersRoles.user', 'user')
        .getMany();

Actually it's returning whole user list. But I need only specified two type of user. That should be filtered with where condition. which is in mysql query.

Upvotes: 1

Views: 1937

Answers (1)

Rasool Khan
Rasool Khan

Reputation: 531

const users = await query
    .select(userRoles.user_id)
    .innerJoin('userRoles.roles', 'roles', 'roles.id = users_roles.role_id')
    .where("roles.role = :adminRole OR roles.role =: superRole", { adminRole: 'ADMIN_ROLE', superRole: 'SUPER_ADMIN_ROLE' })
    .getMany();

I hope this works.

Upvotes: 1

Related Questions