TypeORM中如何从父实体获取子实体类型及属性?
解决方案
1. 在父实体中显式声明type属性
你无法访问type属性的核心原因是:@TableInheritance仅配置了用于区分子类的数据库列,但并未在父实体类中定义对应的属性字段。TypeORM不会自动为这个配置列生成实体属性,需要手动添加:
@Entity() @TableInheritance({ column: { type: "varchar", name: "type" } }) @ObjectType({ isAbstract: false }) export class OrganisationEntity extends BaseEntity { @Field() @Column() name: string; // 新增type属性,与@TableInheritance配置的列对应 @Field() @Column({ type: "varchar", name: "type", nullable: false }) type: string; @Field(() => [UserEntity]) @OneToMany(() => UserEntity, (user) => user.organisation) users: UserEntity[]; }
2. 修正子实体定义(避免重复+指定类型标识)
你的子实体代码存在重复定义MedicalOrganisation的问题,同时建议显式为每个子实体指定type字段的值,避免依赖TypeORM自动生成的类名:
// 给@ChildEntity指定name参数,对应父实体type字段的值 @ChildEntity("medicalOrganisation") @ObjectType() export class MedicalOrganisation extends OrganisationEntity { // 这里可以添加子类独有的属性,比如医疗许可证号 @Field({ nullable: true }) @Column({ nullable: true }) licenceNumber?: string; } @ChildEntity("softwareOrganisation") @ObjectType() export class SoftwareOrganisation extends OrganisationEntity { // 软件组织独有的属性,比如产品线 @Field({ nullable: true }) @Column({ nullable: true }) productLine?: string; }
3. 实现无依赖的类型判断
现在你可以直接通过父实体的type属性做判断,无需引入子实体,完全避免循环引用:
const organisation = await OrganisationEntity.findOne(); if (organisation.type === "medicalOrganisation") { // 处理医疗组织相关逻辑 } else if (organisation.type === "softwareOrganisation") { // 处理软件组织相关逻辑 }
关键说明
- TypeORM会自动维护
type字段的值:保存子实体时,TypeORM会自动将@ChildEntity中指定的name写入数据库type列;查询时会根据该值自动实例化对应的子实体类。 - 若不需要在GraphQL接口暴露
type字段,可去掉@Field()装饰器。
内容的提问来源于stack exchange,提问作者Sid
相关产品推荐
相关产品推荐

