1

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.

dzdmmtf
  • 429
  • 3
  • 11

1 Answers1

2

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.

DogEatDog
  • 2,899
  • 2
  • 36
  • 65
  • This is not achievable using concrete table inheritance instead of single table inheritance? I didn't want to have the notification table in the database. – dzdmmtf Nov 29 '21 at 21:42
  • 1
    Abstract inheritance is a way to create Entities that inherit all of the same properties from 'base' abstract class. For example, if I want all of my Entities to have `created_at`, `updated_at`, `status`, I would use an abstract class so I do not have to rewrite that code that defines those properties within each Entity. [docs](https://orkhan.gitbook.io/typeorm/docs/entity-inheritance). Single Table Inheritance, will allow you to create multiple "types" of the same Entity and save them in the same table in the DB. – DogEatDog Nov 29 '21 at 21:49
  • can you query the parent with a column that is only in a subset of the children entities with single table inheritance? frustrating to have to query each child individually – sf8193 Sep 29 '22 at 07:44