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()