Home > Software design >  TypeORM results to undefined on OneToOne relationship
TypeORM results to undefined on OneToOne relationship

Time:02-22

I'm new to NestJS (I had a bit of experience in Angular). I'm getting undefined when I console.log a JoinTable (the tables are new. I'm tasked to create a new microservice)

So Unit and Hub has One to One relationship.

Here is the unit

  @Entity({
    name: 'units',
  })
  export class UnitEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @OneToOne(() => HubEntity)
    @JoinColumn({name: "hub_id"})
    hub: HubEntity;

FYI I also tried coding it like this:

    @OneToOne(type => HubEntity, hub => hub.unit)
    @JoinColumn({name: "hub_id"})
    hub: HubEntity;

For the HUB:

 @Entity({
    name: 'hubs',
  })
  export class HubEntity {
    @PrimaryGeneratedColumn()
    id: number;
  
    @OneToOne(type => UnitEntity, unit => unit.hub)
    @JoinColumn({name: "hub_id"})
    unit: UnitEntity;

For testing, this is how I consoled it.

async findAllByUnit(unitId: number) {
    const unit = await this.unitRepository.findOne(unitId)

    console.log(unit.hub)
  }

It returns undefined

Please let me know what I'm missing.

Thank you in advance~

CodePudding user response:

You have to include the relationship like this:

await this.unitRepository.findOne(unitId, {
    relations: ['hub']
})
  • Related