简体   繁体   中英

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;

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM