Search code examples
sqltypescriptormnestjstypeorm

TypeORM How to access reference relation field without loading relation entity


As we know, to create ManyToOne/OneToMany relation we have to use @ManyToOne/@OneToMany decorators on a field.

In my project I have two entities: Project and Position.

This is how I created a relation:

@Entity('positions')
export class Position {

  @ManyToOne(() => Project, {
    nullable: false,
    eager: true,
  })
  @JoinColumn()
  project: Project;

}

TypeORM documentation says this code will create projectId FOREIGN KEY column in the database and store a project id in it.

Then when we trying to access project property TypeORM loads a project by the id stored in projectId field.

QUESTION

How can I access that pojectId field without loading a relational entity?

The property projectId does not exists by default in Position entity and if I manually create it it is not populated by projectId column value.

I have tried this way:

  @ManyToOne(() => Project, {
    nullable: false,
    eager: false,
  })
  @JoinColumn()
  project: Project;

  projectId: string;

Solution

  • You can use the @RelationId decorator exported by typeorm. Using your example:

    import {
      Column,
      Entity,
      ManyToOne,
      RelationId,
      JoinColumn,
    } from 'typeorm'
    
    @Entity()
    export class Position {
      @ManyToOne(() => Project, {
        nullable: false,
        eager: false,
      })
      @JoinColumn()
      project: Project;
    
      @Column()
      @RelationId((position: Position) => position.project)
      projectId: string;
    }