How to map joined table column to an entity's field in TypeORM

3.7k Views Asked by At

There are two entities as follow:

// user.entity.ts

@Entity()
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @RelationId((user: User) => user.group)
  groupId: number;

  @Column()
  fullName: string;

  @Column()
  email: string;

  @Column()
  passwordHash: string;

  @ManyToOne(type => Group, group => group.users)
  @JoinColumn()
  group: Group;

  isOwner: boolean;
}
// group.entity.ts

@Entity()
export class Group extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column({ default: false })
  isOwner: boolean;

  @OneToMany(type => User, user => user.group)
  users: User[];
}

I'd like to map the isOwner value of Group to isOwner of User

I tried:

  async findOneById(id: number): Promise<User> {
    return await User.createQueryBuilder('user')
      .leftJoinAndMapOne('user.isOwner', 'user.group', 'group')
      .select(['user.id', 'user.fullName', 'user.email', 'group.isOwner'])
      .getOne();
  }

the result was:

enter image description here

It is possible to achieve that by using @AfterLoad() or with JS or with raw query.

BUT

Is it possible to implement that using the orm on the query level?

1

There are 1 best solutions below

0
On

Something like that could be as a solution:

  findOneById(id: number): Promise<User> {
    return User.createQueryBuilder('user')
      .leftJoinAndMapOne('user.isOwner', 'user.group', 'group')
      .select(['user.id', 'user.fullName', 'user.email', 'group.isOwner AS user.isOwner']) // or probably 'group.isOwner AS user_isOwner'
      .getOne();
  }

And you could look at this answer, hope it would be helpful