在 TypeORM 中使用对父实体的查询查找所有子实体
Finding All Child Entities using Query to Parent Entity in TypeORM
考虑如下基本实体:
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 {}
有没有办法像这样使用对父 class 的查询来查找 NotificationType1 和 NotificationType2 中的所有行?
SELECT * FROM NOTIFICATION;
这个查询return0行,虽然在NotificationType1和NotificationType2表中都有记录。
您应该能够从 superclass Select 并使用如下内容检索所有记录:
import {getConnection} from "typeorm";
const user = await getConnection().createQueryBuilder()
.select("notification")
.from(Notification, "notification");
您还需要将 abstract
class 更改为 @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 {}
考虑如下基本实体:
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 {}
有没有办法像这样使用对父 class 的查询来查找 NotificationType1 和 NotificationType2 中的所有行?
SELECT * FROM NOTIFICATION;
这个查询return0行,虽然在NotificationType1和NotificationType2表中都有记录。
您应该能够从 superclass Select 并使用如下内容检索所有记录:
import {getConnection} from "typeorm";
const user = await getConnection().createQueryBuilder()
.select("notification")
.from(Notification, "notification");
您还需要将 abstract
class 更改为 @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 {}