【问题标题】:Finding All Child Entities using Query to Parent Entity in TypeORM在 TypeORM 中使用查询父实体查找所有子实体
【发布时间】:2022-01-06 16:48:36
【问题描述】:

考虑如下基础实体:

export abstract class Notification {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({type: "date",nullable: false})
  seenAt: Date;

  @Column({ type: "integer", nullable: false })
  priority: number;
}

还有两个子实体如下:

@Entity()
export class NotificationType1 extends Notification {}

@Entity()
export class NotificationType2 extends Notification {}

有没有办法像这样使用对父类的查询来查找 NotificationType1 和 NotificationType2 中的所有行?

SELECT * FROM NOTIFICATION;

此查询返回 0 行,尽管 NotificationType1 和 NotificationType2 表中有记录。

【问题讨论】:

    标签: nestjs typeorm class-table-inheritance


    【解决方案1】:

    您应该能够从超类中选择并检索所有记录,如下所示:

    import {getConnection} from "typeorm"; 
    
    const user = await getConnection().createQueryBuilder() 
    .select("notification") 
    .from(Notification, "notification");
    

    您还需要将 abstract 类更改为 @TableInheritance 以利用 Single Table Inheritance.

    此代码:

    export abstract class Notification {
      @PrimaryGeneratedColumn()
      id: number;
    
      @Column({type: "date",nullable: false})
      seenAt: Date;
    
      @Column({ type: "integer", nullable: false })
      priority: number;
    }
    

    会变成:

    @Entity()
    @TableInheritance({ column: { type: "varchar", name: "type" } })
    export class Notification {
      @PrimaryGeneratedColumn()
      id: number;
    
      @Column({type: "date",nullable: false})
      seenAt: Date;
    
      @Column({ type: "integer", nullable: false })
      priority: number;
    }
    

    还有子实体:

    @ChildEntity()
    export class NotificationType1 extends Notification {}
    

    docs have on single table inheritance

    【讨论】:

    • 这不是使用具体表继承而不是单表继承来实现的吗?我不想在数据库中有通知表。
    • 抽象继承是一种创建实体的方法,这些实体从“基”抽象类继承所有相同的属性。例如,如果我希望我的所有实体都具有created_atupdated_atstatus,我将使用抽象类,这样我就不必重写定义每个实体中这些属性的代码。 docs。单表继承,将允许您创建同一个实体的多个“类型”并将它们保存在数据库的同一个表中。
    猜你喜欢
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多