TypeORM query nested relationship

TypeORM query nested relationship

Sometimes you have a data model where object has a relationship few levels deep.

For example:

Person->job->jobType

It is a style preference, but I like to use TypeORM as active record. So all my entities ussualy extends BaseEntity

@Entity('Person')
export class Person extends BaseEntity {
	// Entity properties here
}

So to reference nested relationships you just have to do:

let personsWithJobType = await Person.find({
  where: {
    id: id
  },
  join: {
    alias: "person",
    leftJoinAndSelect: {
      "jobs": "person.jobs",
      "jobType": "jobs.jobType"
    }
  }
})

TypeORM cool & nice javascript package to interact database, but from time to time its tricky to get it right. So I hope this helps!

Have a nice day!

Show Comments