Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 956
Martin Ocando Avatar asked Oct 14 '25 04:10

Martin Ocando


1 Answers

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();
like image 161
leonardfactory Avatar answered Oct 16 '25 18:10

leonardfactory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!