'How to query for manyTomany relation in typeorm?

I m trying to fetch user details using typeorm in nestjs below are the tables in mysql database

user table

role table

id (PK) name
1 ADMIN
2 USER

user_role table

user_id (FK) role_id (FK)
1 1
1 2
2 1

Expected result:

{
  id: 1,
  email: 'a@mail',
  roles: ['ADMIN', 'USER']
}

My code gets me the expected results

  1. I get user with email id
  2. then I find all the roles which are associated with the user
  3. lastly append the roles with user object and return

Is there any better approach for this problem

Here is my code:

  async getUserByEmail(email) {
    const user = await getRepository(UserEntity).createQueryBuilder('user')
      .select([
        'user.id AS id',
        'user.email AS email',
      ])
      .where('user.email = :email', {
        email: email,
      })
      .getRawOne()


    const roles = await getRepository(UserEntity).createQueryBuilder('user')
      .leftJoin('user.roles', 'roles')
      .select(['roles.name AS role'])
      .where('user.email = :email', {
        email: email
      })
      .getRawMany()

    const userRoles = []
    roles.forEach(rl => {
      userRoles.push(rl.role)
    })

    user.roles = userRoles

    return user
  }

Thanks in advance : )



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source