nestjstypeormclass-table-inheritance

Finding All Child Entities using Query to Parent Entity in TypeORM


Consider a base entity as below:

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

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

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

and two child entities as below:

@Entity()
export class NotificationType1 extends Notification {}

and

@Entity()
export class NotificationType2 extends Notification {}

Is there a way to find all rows in NotificationType1 and NotificationType2 using a query to the parent class like this?

SELECT * FROM NOTIFICATION;

This query return 0 rows, although there are records in NotificationType1 and NotificationType2 tables.


Solution

  • You should be able to Select from the superclass and retrieve all the records with something like this:

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

    You also need to change your abstract class to @TableInheritance to leverage Single Table Inheritance.

    This Code:

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

    Would become:

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

    And the Child Entity:

    @ChildEntity()
    export class NotificationType1 extends Notification {}
    

    The docs have on single table inheritance.