Search code examples
node.jspostgresqltypescripttypeorm

Typeorm: paginate relations


I have these two entities:

@Entity()
@Unique(["userName"])
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @Length(4, 20)
  userName: string;

  @ManyToMany(type => League, league => league.members)
  leagues: League[];

}
@Entity()
export class League {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @Length(3, 50)
  name: string;

  @Column()
  @Length(0, 200)
  description: string;

  @Column()
  @Length(4, 20)
  country: string;

  @ManyToMany(type => User)
  @JoinTable()
  members: User[];
}

But a league can have many members so it is not optimal to bring all the members of a league into one call. Is it possible to paginate the relation of members of a league?

My models are wrong?

I'm using typeorm@^0.2.24 and nodejs with typescript


Solution

  • It is currently not supported to paginate only a relationship, when using find methods from one Entity. In this case just use the QueryBuilder. You can see the QueryBuilder documentation here.

    So, in this case you can use:

    // This will be paginated
    const leagueMembers = await connection
        .createQueryBuilder(User, "user")
        .leftJoin("user.leagues", "league", "league.id = :leagueId"; { leagueId })
        .orderBy("user.id")
        .skip(..)
        .take(..)
        .getMany();