Home > Software engineering >  How do I search in the postgresql using Typeorm and return the mutated value for relation?
How do I search in the postgresql using Typeorm and return the mutated value for relation?

Time:02-02

I have a User entity with a Role relationship in an application Nestjs.

@Entity()
class User {
  ...
  @ManyToOne(() => Role, {
    eager: true,
  })
  role?: Role;
}
@Entity()
export class Role extends EntityHelper {
  @PrimaryColumn()
  id: number;

  @Column()
  name?: string;
}

when I want get users from the DB I do:

this.usersRepository.find({ 
      relations: {
        role: true,
      },
    })

and I get data like this:

{ id: 1,  name: "John", role:  { id: 2, name: "user" }}

but I don't want to get the role as an object, I just want the name from this Example:

{ id: 1,  name: "John", role: "user" }

So, my question is how can I get the relation and return only the value of { ... role: "user" }?

CodePudding user response:

You can achieve it by using QueryBuilder:

this.usersRepository.createQueryBuilder('User')
  .innerJoinAndSelect('User.role', 'Role')
  .select(['Role.name as role', 'User.id as id'])
  .getRawMany()
  • Related