Skip to content

Instantly share code, notes, and snippets.

@IslamWahid
Created January 28, 2020 13:38
Show Gist options
  • Save IslamWahid/16476c3b3edf9f3ab556de31c03e2ef3 to your computer and use it in GitHub Desktop.
Save IslamWahid/16476c3b3edf9f3ab556de31c03e2ef3 to your computer and use it in GitHub Desktop.
TypeORM tricks

TypeORM tricks

Finding entity with with relation condition

There's a workaround for filtering based on relation fields for findOne()/find() methods that I've discovered recently. The problem with filtering related table fields only exists for ObjectLiteral-style where, while string conditions work perfectly.

Assume that we have two entities – User and Role, user belongs to one role, role has many users:

@Entity()
export class User {
  name: string;

  @ManyToOne(() => Role, role => role.users)
  role: Role;
}

@Entity()
export class Role {
  @OneToMany(() => User, user => user.role)
  users: User[];
}

Now we can call findOne()/find() methods of EntityManager or repository:

roleRepository.find({
  join: { alias: 'roles', innerJoin: { users: 'roles.users' } },
  where: qb => {
    qb.where({ // Filter Role fields
      a: 1,
      b: 2
    }).andWhere('users.name = :userName', { userName: 'John Doe' }); // Filter related field
  }
});

You can omit the join part if you've marked your relation as an eager one.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment