MikroORM7.2 中文文档
建模/继承映射
已译 96/96

继承映射

映射超类

映射超类是一个抽象或具体的类,它为其子类提供持久化实体状态与映射信息,但它本身不是实体。通常,这类映射超类的目的是定义多个实体类所共有的状态与映射信息。

映射超类与普通的非映射类一样,可以出现在一段映射继承层级(通过单表继承)的中间位置。

映射超类不能是实体,它不可查询,并且由映射超类定义的持久化关系必须是单向的(只有拥有方)。这意味着映射超类上完全无法使用一对多关联。此外,多对多关联只有在映射超类当前恰好只被一个实体使用时才可行。若需要更进一步的继承支持,必须使用单表继承特性。

另请注意,你不能使用泛型来定义任何关系。这意味着你不能在基础实体中用一个泛型类型参数作为某个关系的目标。

const p = defineEntity.properties;

// 映射超类(抽象实体,不会拥有自己的表)
const PersonSchema = defineEntity({
  name: 'Person',
  abstract: true,
  properties: {
    mapped1: p.number(),
    mapped2: p.string(),
    toothbrush: () => p.oneToOne(Toothbrush),
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    id: p.number().primary(),
    name: p.string(),
  },
});

export const Toothbrush = defineEntity({
  name: 'Toothbrush',
  properties: {
    id: p.number().primary(),
    // ... 更多字段
  },
});

export class Person extends PersonSchema.class {}
PersonSchema.setClass(Person);

在 defineEntity + class 模式下使用 extends 时,基类的属性初始化器会通过 super() 自动执行。详见通过 extends 复用基类属性。

const p = defineEntity.properties;

// 映射超类(抽象实体,不会拥有自己的表)
export const Person = defineEntity({
  name: 'Person',
  abstract: true,
  properties: {
    mapped1: p.number(),
    mapped2: p.string(),
    toothbrush: () => p.oneToOne(Toothbrush),
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    id: p.number().primary(),
    name: p.string(),
  },
});

export const Toothbrush = defineEntity({
  name: 'Toothbrush',
  properties: {
    id: p.number().primary(),
    // ... 更多字段
  },
});

export type IPerson = InferEntity<typeof Person>;
export type IEmployee = InferEntity<typeof Employee>;
export type IToothbrush = InferEntity<typeof Toothbrush>;
// 不要在基类(映射超类)上使用 @Entity 装饰器
// 我们也可以使用 @Entity({ abstract: true })
export abstract class Person {

  @Property()
  mapped1!: number;

  @Property()
  mapped2!: string;

  @OneToOne()
  toothbrush!: Toothbrush;

  // ... 更多字段与方法
}

@Entity()
export class Employee extends Person {

  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;

  // ... 更多字段与方法

}

@Entity()
export class Toothbrush {

  @PrimaryKey()
  id!: number;

  // ... 更多字段与方法

}

对应数据库 schema 的 DDL 大致如下(这是针对 SQLite 的):

create table `employee` (
  `id` int unsigned not null auto_increment primary key,
  `name` varchar(255) not null, `mapped1` integer not null,
  `mapped2` varchar(255) not null,
  `toothbrush_id` integer not null
);

从这段 DDL 可以看到,实体子类只有一张表。映射超类的所有映射都被子类继承,效果如同它们直接定义在该子类上。

单表继承

对 STI 的支持是在 4.0 版本加入的

单表继承是一种继承映射策略,层级中的所有类都被映射到同一张数据库表。为了区分哪一行代表层级中的哪个类型,会使用一个所谓的判别列。

const PersonSchema = defineEntity({
  name: 'Person',
  discriminatorColumn: 'discr',
  discriminatorMap: { person: 'Person', employee: 'Employee' },
  properties: {
    // ...
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    // ...
  },
});

export class Person extends PersonSchema.class {}
PersonSchema.setClass(Person);
export const Person = defineEntity({
  name: 'Person',
  discriminatorColumn: 'discr',
  discriminatorMap: { person: 'Person', employee: 'Employee' },
  properties: {
    // ...
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    // ...
  },
});
@Entity({
  discriminatorColumn: 'discr',
  discriminatorMap: { person: 'Person', employee: 'Employee' },
})
export class Person {
  // ...
}

@Entity()
export class Employee extends Person {
  // ...
}

需要注意的几点:

  • discriminatorColumn 选项必须指定在映射实体层级中最顶层的类上。
  • discriminatorMap 指定判别列的哪些取值标识某一行属于某个特定类型。在上面的例子中,值 person 标识该行属于 Person 类型,employee 标识该行属于 Employee 类型。
  • 映射实体层级中的所有实体类(包括最顶层的类)都应当在 discriminatorMap 中指定。上面例子中包含了 Person 类。
  • 你可以把抽象类用作根实体 —— 此时根类不应出现在判别映射中。
  • 如果没有提供判别映射,则会自动生成。自动生成的判别映射包含那些在常规实体情况下本会使用的表名。

使用 discriminatorValue 代替 discriminatorMap

如上所述,判别映射可以自动生成。这种情况下,你可能想控制映射中所使用的标记。为此,你可以在子实体上使用 discriminatorValue:

const PersonSchema = defineEntity({
  name: 'Person',
  discriminatorColumn: 'discr',
  discriminatorValue: 'person',
  properties: {
    // ...
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  discriminatorValue: 'employee',
  properties: {
    // ...
  },
});

export class Person extends PersonSchema.class {}
PersonSchema.setClass(Person);
export const Person = defineEntity({
  name: 'Person',
  discriminatorColumn: 'discr',
  discriminatorValue: 'person',
  properties: {
    // ...
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  discriminatorValue: 'employee',
  properties: {
    // ...
  },
});
@Entity({
  discriminatorColumn: 'discr',
  discriminatorValue: 'person',
})
export class Person {
  // ...
}

@Entity({
  discriminatorValue: 'employee',
})
export class Employee extends Person {
  // ...
}

显式判别列

discriminatorColumn 指定一个特殊列的名称,用于定义某一行应当以哪个类表示。它会为我们自动定义,并且保持隐藏(不会被水合为常规属性)。

另一方面,显式定义该列也完全没问题。这时请改用 discriminator 选项(它指的是实体上的属性名)—— 列名由命名策略从该属性推导得出。显式定义它可以让你:

  • 按类型查询,例如 em.find(Person, { type: { $ne: 'employee' } }
  • 把该列包含在序列化响应中

discriminator 是实体上的属性名;discriminatorColumn 是底层列名的可选覆盖项。当省略 discriminator 时,discriminatorColumn 同时也被用作属性名(旧有行为)。@Embeddable 同理。

下面的示例展示了如何显式定义判别符,以及根实体为抽象类的版本。

const BasePersonSchema = defineEntity({
  name: 'BasePerson',
  abstract: true,
  discriminator: 'type',
  discriminatorMap: { person: 'Person', employee: 'Employee' },
  properties: {
    type: p.enum(['person', 'employee'] as const),
  },
});

export const Person = defineEntity({
  name: 'Person',
  extends: BasePerson,
  properties: {
    // ...
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    // ...
  },
});

export class BasePerson extends BasePersonSchema.class {}
BasePersonSchema.setClass(BasePerson);
export const BasePerson = defineEntity({
  name: 'BasePerson',
  abstract: true,
  discriminator: 'type',
  discriminatorMap: { person: 'Person', employee: 'Employee' },
  properties: {
    type: p.enum(['person', 'employee'] as const),
  },
});

export const Person = defineEntity({
  name: 'Person',
  extends: BasePerson,
  properties: {
    // ...
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    // ...
  },
});
@Entity({
  discriminator: 'type',
  discriminatorMap: { person: 'Person', employee: 'Employee' },
})
export abstract class BasePerson {

  @Enum()
  type!: 'person' | 'employee';

}

@Entity()
export class Person extends BasePerson {
  // ...
}

@Entity()
export class Employee extends Person {
  // ...
}

如果你想在抽象实体上使用 discriminatorValue,需要把该实体标记为 abstract: true,这样它就能从判别映射中被跳过:

const BasePersonSchema = defineEntity({
  name: 'BasePerson',
  abstract: true,
  discriminator: 'type',
  properties: {
    type: p.enum(['person', 'employee'] as const),
  },
});

export const Person = defineEntity({
  name: 'Person',
  extends: BasePerson,
  discriminatorValue: 'person',
  properties: {
    // ...
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  discriminatorValue: 'employee',
  properties: {
    // ...
  },
});

export class BasePerson extends BasePersonSchema.class {}
BasePersonSchema.setClass(BasePerson);
export const BasePerson = defineEntity({
  name: 'BasePerson',
  abstract: true,
  discriminator: 'type',
  properties: {
    type: p.enum(['person', 'employee'] as const),
  },
});

export const Person = defineEntity({
  name: 'Person',
  extends: BasePerson,
  discriminatorValue: 'person',
  properties: {
    // ...
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  discriminatorValue: 'employee',
  properties: {
    // ...
  },
});
@Entity({
  discriminator: 'type',
  abstract: true,
})
export abstract class BasePerson {

  @Enum()
  type!: 'person' | 'employee';

}

@Entity({ discriminatorValue: 'person' })
export class Person extends BasePerson {
  // ...
}

@Entity({ discriminatorValue: 'employee' })
export class Employee extends Person {
  // ...
}

设计期考量

当类型层级相当简单且稳定时,这种映射方式效果很好。向层级中添加新类型、向已有超类型添加字段,都只是给表增加新列而已,不过在大型部署中这可能对数据库内的索引与列布局产生不利影响。

性能影响

该策略在跨层级所有类型或针对特定类型查询时非常高效。无需表连接,只需一个列出类型标识符的 WHERE 子句。尤其是,涉及采用该映射策略的类型的关系性能非常出色。

SQL Schema 考量

要让单表继承在使用遗留数据库 schema 或自建数据库 schema 的场景下正常工作,你必须确保:所有不在根实体中、而位于各个子实体中的列都必须允许 null 值。带 NOT NULL 约束的列必须位于单表继承层级的根实体上。

本部分文档深受 doctrine docs 启发,因为这里的行为与之几乎完全相同。

另见:多态关系

如果你需要一个可以指向多个无关实体类型(各自拥有自己的表)的关系,请考虑使用多态关系而不是继承。

特性单表继承多态关系
存储所有类型共用一张表每个类型有自己的表
使用场景实体共享公共字段/行为指向无关实体的灵活外键
继承必需(公共基类)非必需
外键带引用完整性的原生外键约束无外键约束(无数据库层面的完整性)
示例Cat、Dog 继承 AnimalLike 指向 Post 或 Comment

每类型一张表继承(TPT)

每类型一张表继承(也称为类表继承)是一种继承映射策略,层级中的每个类都有自己专属的数据库表。与所有实体共享一张含大量可空列的表的 STI 不同,TPT 会创建:

  • 每个实体一张独立表,只包含它自己的属性
  • 子表持有指向父表的外键(使用相同的主键值)
  • ON DELETE CASCADE 确保父记录被删除时正确清理

配置

在层级的根实体上使用 inheritance: 'tpt':

const PersonSchema = defineEntity({
  name: 'Person',
  abstract: true,
  inheritance: 'tpt',
  properties: {
    id: p.number().primary(),
    name: p.string(),
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    department: p.string(),
  },
});

export const Customer = defineEntity({
  name: 'Customer',
  extends: Person,
  properties: {
    loyaltyPoints: p.number(),
  },
});

export class Person extends PersonSchema.class {}
PersonSchema.setClass(Person);
export const Person = defineEntity({
  name: 'Person',
  abstract: true,
  inheritance: 'tpt',
  properties: {
    id: p.number().primary(),
    name: p.string(),
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    department: p.string(),
  },
});

export const Customer = defineEntity({
  name: 'Customer',
  extends: Person,
  properties: {
    loyaltyPoints: p.number(),
  },
});
@Entity({ inheritance: 'tpt' })
export abstract class Person {

  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;

}

@Entity()
export class Employee extends Person {

  @Property()
  department!: string;

}

@Entity()
export class Customer extends Person {

  @Property()
  loyaltyPoints!: number;

}

生成的 Schema

上述配置会生成如下 schema:

CREATE TABLE person (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);

CREATE TABLE employee (
  id INTEGER PRIMARY KEY REFERENCES person(id) ON DELETE CASCADE,
  department TEXT NOT NULL
);

CREATE TABLE customer (
  id INTEGER PRIMARY KEY REFERENCES person(id) ON DELETE CASCADE,
  loyalty_points INTEGER NOT NULL
);

TPT 如何工作

INSERT 操作

插入 TPT 实体时,MikroORM 会自动向层级中的所有表插入数据,从根表开始:

const employee = em.create(Employee, {
  name: 'John Doe',
  department: 'Engineering',
});
await em.flush();

// 执行:
// INSERT INTO person (name) VALUES ('John Doe') -- 返回 id=1
// INSERT INTO employee (id, department) VALUES (1, 'Engineering')

UPDATE 操作

更新会被优化为只修改包含变更属性的表:

employee.department = 'Sales'; // 只更新 employee 表
employee.name = 'Jane Doe';    // 只更新 person 表
await em.flush();

DELETE 操作

从根表删除会通过外键约束自动级联到子表:

em.remove(employee);
await em.flush();

// 执行:
// DELETE FROM person WHERE id = 1
// (employee 行会通过 ON DELETE CASCADE 自动删除)

SELECT 操作

查询 TPT 实体时,MikroORM 会自动 join 所有父表:

const employees = await em.find(Employee, { department: 'Engineering' });

// 执行:
// SELECT e0.*, p1.*
// FROM employee e0
// INNER JOIN person p1 ON e0.id = p1.id
// WHERE e0.department = 'Engineering'

多层继承

TPT 支持深层继承层级。每一层都会增加一张表与一次 join:

const PersonSchema = defineEntity({
  name: 'Person',
  abstract: true,
  inheritance: 'tpt',
  properties: {
    id: p.number().primary(),
    name: p.string(),
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    department: p.string(),
  },
});

export const Manager = defineEntity({
  name: 'Manager',
  extends: Employee,
  properties: {
    teamSize: p.number(),
  },
});

export class Person extends PersonSchema.class {}
PersonSchema.setClass(Person);
export const Person = defineEntity({
  name: 'Person',
  abstract: true,
  inheritance: 'tpt',
  properties: {
    id: p.number().primary(),
    name: p.string(),
  },
});

export const Employee = defineEntity({
  name: 'Employee',
  extends: Person,
  properties: {
    department: p.string(),
  },
});

export const Manager = defineEntity({
  name: 'Manager',
  extends: Employee,
  properties: {
    teamSize: p.number(),
  },
});
@Entity({ inheritance: 'tpt' })
export abstract class Person {
  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;
}

@Entity()
export class Employee extends Person {
  @Property()
  department!: string;
}

@Entity()
export class Manager extends Employee {
  @Property()
  teamSize!: number;
}

这会生成三张表,外键串成一条链:

CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE employee (id INTEGER PRIMARY KEY REFERENCES person(id) ON DELETE CASCADE, department TEXT NOT NULL);
CREATE TABLE manager (id INTEGER PRIMARY KEY REFERENCES employee(id) ON DELETE CASCADE, team_size INTEGER NOT NULL);

查询 Manager 会 join 全部三张表:

const managers = await em.find(Manager, {});

// SELECT m0.*, e1.*, p2.*
// FROM manager m0
// INNER JOIN employee e1 ON m0.id = e1.id
// INNER JOIN person p2 ON e1.id = p2.id

设计期考量

TPT 适合以下情况:

  • Schema 规范化很重要 —— 每张表只包含相关列,并带有恰当的 NOT NULL 约束
  • 子类型拥有大量独有属性 —— 避免出现含大量可空列的宽表
  • 你需要强制保证数据完整性 —— 外键确保跨层级的引用完整性

TPT 可能不适合以下情况:

  • 你经常跨整个层级查询 —— 需要跨所有表做 join
  • 读密集负载对性能要求很高 —— 对多态查询而言 STI 可能更快
  • 层级非常深 —— 每一层都会增加一次 join

性能影响

  • 写入:由于需要多条 INSERT/UPDATE 语句,比 STI 略慢
  • 读取特定类型:需要 join,但只返回相关数据
  • 多态查询:查询基类时(例如 em.find(Person, {})),ORM 会 LEFT JOIN 所有后代表以确定具体类型。对于叶子类型很多的层级,这可能产生很宽的查询。如果这成为瓶颈,请改为直接查询具体类
  • Schema 规模:表更多,但每张表更窄、规范化程度更好

STI 与 TPT 对比

方面STITPT
表整个层级一张表每个实体一张表
列全部列,许多可空仅自有属性,约束得当
INSERT单条语句多条语句(先父后子)
SELECT单表扫描跨层级 JOIN
Schema反规范化规范化
最适合简单层级、读密集复杂层级、有完整性需求的写密集场景

限制

  • 删除级联与生命周期钩子:子表行通过数据库层面的 ON DELETE CASCADE 删除。这意味着 beforeDelete/afterDelete 钩子只会为被显式移除的实体触发 —— 不会为被数据库级联的子表行触发。如果你需要层级中每张表都触发钩子,请为每张表发起显式删除。
  • 软删除:由于删除级联由数据库处理,软删除模式(例如用 @Filter 隐藏已删除行)不会自动感知 TPT。即使父实体使用了软删除过滤器,数据库的 CASCADE 仍会物理删除子行。
  • Schema 回调作用域:TPT 实体的索引表达式、检查约束与生成列回调只能访问该实体自己表中的列。你无法在这些回调中引用来自父表的继承列。
  • 自定义判别列:TPT 在查询时使用计算出来的判别符(CASE WHEN)。与 STI 不同,你无法指定自定义的持久化判别列。

混用 STI 与 TPT

在同一继承层级中混用 STI 与 TPT 不受支持,会导致校验错误。每个层级必须始终使用同一种策略。