Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

417
Views
Nestjs typeorm relation order and limit elements

I am new to relations and typeorm. And now have some troubles with them. And now a little confused. Is it possible in typeorm sort relation by id or createdDate without mapping it and to have limit elements? My code example below:

person.entity

@Entity()
export class Person {
  @PrimaryGeneratedColumn()
  public id!: number;

  @Column({ type: 'varchar', length: 120 })
  public firstName: string;

  @Column({ type: 'varchar', length: 120 })
  public lastName: string;

  @Column({ type: 'varchar', length: 13 })
  public phone: string;

  @Column({ type: 'varchar', length: 500 })
  public place: string;

  @Column({ type: 'boolean', default: false })
  public isDeleted: boolean;

  @OneToMany(() => Event, (event) => event.person, {
    onDelete: 'SET NULL',
  })
  public events: Event[];

  @CreateDateColumn({ type: 'timestamp' })
  public createdAt!: Date;

  @UpdateDateColumn({ type: 'timestamp' })
  public updatedAt!: Date;
}

event.entity

@Entity()
export class Event {
  @PrimaryGeneratedColumn()
  public id!: number;

  @ManyToOne(() => Person, (person) => person.id, {
    onDelete: 'CASCADE',
  })
  public person!: Person;

  @ManyToOne(() => User, (user) => user.id, {
    onDelete: 'CASCADE',
  })
  public user!: User;

  @CreateDateColumn({ type: 'timestamp' })
  public createdAt!: Date;

  @UpdateDateColumn({ type: 'timestamp' })
  public updatedAt!: Date;
}

My code for sorting

  // get persons and sort events
  public async getALlPersons(): Promise<Person[]> {
    return this.repository
      .find({
        relations: ['events'],
        order: {
          createdAt: 'DESC',
        },
      })
      .then((persons) =>
        persons.map((person) => {
          person.events.sort((a, b) => b.id - a.id);
          return person;
        }),
      );
  }

And how to limit the number of events per person, for example I want to show only 10 events?

Thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There is a typeorm issue related to this: https://github.com/typeorm/typeorm/issues/89.

But in summary, it is not possible.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!