简体   繁体   English

TypeORM 如何在不加载关系实体的情况下访问引用关系字段

[英]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.众所周知,要创建 ManyToOne/OneToMany 关系,我们必须在字段上使用 @ManyToOne/@OneToMany 装饰器。

In my project I have two entities: Project and Position .在我的项目中,我有两个实体: ProjectPosition

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. TypeORM 文档说此代码将在数据库中创建projectId FOREIGN KEY列并在其中存储项目 ID。

Then when we trying to access project property TypeORM loads a project by the id stored in projectId field.然后,当我们尝试访问project属性时,TypeORM 通过存储在projectId字段中的 id 加载项目。

QUESTION问题

How can I access that pojectId field without loading a relational entity?如何在不加载关系实体的情况下访问该pojectId字段?

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.默认情况下,属性projectIdPosition实体中不存在,如果我手动创建它,它不会由projectId列值填充。

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 .您可以使用@RelationId导出的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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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