实体关系建模
MikroORM 中有 4 种实体关系类型:
- ManyToOne
- OneToMany
- OneToOne
- ManyToMany
关系可以是单向的,也可以是双向的。单向关系只在一端定义(拥有方)。双向关系在两端都有定义,其中一端是拥有方(引用存储在这一端),通过 inversedBy 属性指向反向端。在反向端,你用 mappedBy 属性指回拥有方:
建模双向关系时,你也可以省略
inversedBy属性,只在反向端定义mappedBy就足够了,它会被自动接线。
ManyToOne
当前实体的多个实例指向被引用实体的一个实例。
定义该关系有多种方式,以下写法完全等价:
import { defineEntity, p } from '@mikro-orm/core';
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author),
},
});
export type IBook = InferEntity<typeof Book>;@Entity()
export class Book {
@ManyToOne(() => Author) // 你需要通过回调指定类型
author1!: Author;
@ManyToOne({ entity: () => Author }) // 或使用选项对象
author2!: Author;
}@Entity()
export class Book {
@ManyToOne() // 普通的装饰器就够了,类型会通过 ts-morph 自动嗅探!
author!: Author;
}你也可以指定对该实体的操作应如何级联到被引用实体。
让关系具备类型安全
默认情况下,@ManyToOne 属性被类型化为裸实体,这意味着 TypeScript 不知道它是否已被 populate。有三种方式可以增加编译期安全性:
Ref<T>—— 在运行时把实体包装进Reference,并添加.$/.get()/.load()访问器。通过{ ref: true }或.ref()使用。参见类型安全关系 →Ref包装器。LazyRef<T>—— 纯类型标记,运行时值仍是普通实体(无包装器)。在Loaded<>收窄之前限制对非主键的访问,加载后也没有.$间接层。通过.lazyRef()使用,或把属性声明为LazyRef<T>。参见LazyRef<T>。- 普通关系 —— 没有编译期的 populate 状态安全性,对来自其他 ORM 的用户最为熟悉。
同样的说明也适用于 @OneToOne。
OneToMany
当前实体的一个实例拥有被引用实体的多个实例(引用)。
同样地,以下写法完全等价:
import { defineEntity, p } from '@mikro-orm/core';
const AuthorSchema = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
books: () => p.oneToMany(Book).mappedBy('author'),
},
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const Author = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
books: () => p.oneToMany(Book).mappedBy('author'),
},
});
export type IAuthor = InferEntity<typeof Author>;@Entity()
export class Author {
@OneToMany(() => Book, book => book.author)
books1 = new Collection<Book>(this);
@OneToMany({ mappedBy: book => book.author }) // 被引用的实体类型同样可以被嗅探
books2 = new Collection<Book>(this);
@OneToMany({ entity: () => Book, mappedBy: 'author', orphanRemoval: true })
books3 = new Collection<Book>(this);
}@Entity()
export class Author {
@OneToMany(() => Book, book => book.author)
books = new Collection<Book>(this);
}如你所见,OneToMany 是 ManyToOne(拥有方)的反向端。关于集合如何工作的更多内容可以在集合页面找到。
你也可以指定对该实体的操作应如何级联到被引用实体。还有一种更激进的移除模式叫做孤儿移除(即 books3 示例)。
OneToOne
当前实体的一个实例指向被引用实体的一个实例。
这是 ManyToOne 的一种变体,两端始终各只有一个实体。这意味着外键列也是唯一的。
拥有方
import { defineEntity, p } from '@mikro-orm/core';
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
// 当 `owner/inversedBy/mappedBy` 都未提供时,它会被视为拥有方
bestFriend1: () => p.oneToOne(User),
// 带 `inversedBy` 的一端是拥有方,要定义反向端请使用 `mappedBy`
bestFriend2: () => p.oneToOne(User).inversedBy('bestFriend1'),
// 你需要用 `owner: true` 显式标记拥有方
bestFriend3: () => p.oneToOne(User).owner(),
},
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
// 当 `owner/inversedBy/mappedBy` 都未提供时,它会被视为拥有方
bestFriend1: () => p.oneToOne(User),
// 带 `inversedBy` 的一端是拥有方,要定义反向端请使用 `mappedBy`
bestFriend2: () => p.oneToOne(User).inversedBy('bestFriend1'),
// 你需要用 `owner: true` 显式标记拥有方
bestFriend3: () => p.oneToOne(User).owner(),
},
});
export type IUser = InferEntity<typeof User>;@Entity()
export class User {
// 当 `owner/inversedBy/mappedBy` 都未提供时,它会被视为拥有方
@OneToOne()
bestFriend1!: User;
// 带 `inversedBy` 的一端是拥有方,要定义反向端请使用 `mappedBy`
@OneToOne({ inversedBy: 'bestFriend1' })
bestFriend2!: User;
// 按这种方式定义时,你需要用 `owner: true` 显式标记拥有方
@OneToOne(() => User, user => user.bestFriend2, { owner: true })
bestFriend3!: User;
}@Entity()
export class User {
// 当 `owner/inversedBy/mappedBy` 都未提供时,它会被视为拥有方
@OneToOne()
bestFriend1!: User;
// 带 `inversedBy` 的一端是拥有方,要定义反向端请使用 `mappedBy`
@OneToOne({ inversedBy: 'bestFriend1' })
bestFriend2!: User;
// 按这种方式定义时,你需要用 `owner: true` 显式标记拥有方
@OneToOne(() => User, user => user.bestFriend2, { owner: true })
bestFriend3!: User;
}反向端
import { defineEntity, p } from '@mikro-orm/core';
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
// 反向端必须通过 `mappedBy` 指向拥有方
bestFriend1: () => p.oneToOne(User).mappedBy('bestFriend1').orphanRemoval(),
},
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
// 反向端必须通过 `mappedBy` 指向拥有方
bestFriend1: () => p.oneToOne(User).mappedBy('bestFriend1').orphanRemoval(),
},
});
export type IUser = InferEntity<typeof User>;@Entity()
export class User {
@OneToOne({ mappedBy: 'bestFriend1', orphanRemoval: true })
bestFriend1!: User;
@OneToOne(() => User, user => user.bestFriend2, { orphanRemoval: true })
bestFriend2!: User;
}@Entity()
export class User {
@OneToOne({ mappedBy: 'bestFriend1', orphanRemoval: true })
bestFriend1!: User;
@OneToOne(() => User, user => user.bestFriend2, { orphanRemoval: true })
bestFriend2!: User;
}如你所见,关系也可以是自引用的(所有类型都支持。OneToOne 同样支持孤儿移除)。
ManyToMany
当前实体的多个实例指向被引用实体的多个实例。
下面是定义 ManyToMany 关系的示例:
拥有方
import { defineEntity, p } from '@mikro-orm/core';
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
// 当 `owner/inversedBy/mappedBy` 都未提供时,它会被视为拥有方
tags1: () => p.manyToMany(BookTag),
// 或者你可以用 `owner()` 显式标记拥有方
tags2: () => p.manyToMany(BookTag).inversedBy('books').owner(),
// 要定义单向多对多,只需省略 `mappedBy`
friends: () => p.manyToMany(Author),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
// 当 `owner/inversedBy/mappedBy` 都未提供时,它会被视为拥有方
tags1: () => p.manyToMany(BookTag),
// 或者你可以用 `owner()` 显式标记拥有方
tags2: () => p.manyToMany(BookTag).inversedBy('books').owner(),
// 要定义单向多对多,只需省略 `mappedBy`
friends: () => p.manyToMany(Author),
},
});
export type IBook = InferEntity<typeof Book>;@Entity()
export class Book {
// 当 `owner/inversedBy/mappedBy` 都未提供时,它会被视为拥有方
@ManyToMany(() => BookTag)
tags1 = new Collection<BookTag>(this);
// 或者你可以用 `owner: true` 显式标记拥有方
@ManyToMany(() => BookTag, 'books', { owner: true })
tags2 = new Collection<BookTag>(this);
// 要定义单向多对多,只需省略 `mappedBy`
@ManyToMany(() => Author)
friends = new Collection<Author>(this);
}@Entity()
export class Book {
// 当 `owner/inversedBy/mappedBy` 都未提供时,它会被视为拥有方
@ManyToMany()
tags1 = new Collection<BookTag>(this);
// 或者你可以用 `owner: true` 显式标记拥有方
@ManyToMany({ inversedBy: 'books', owner: true })
tags2 = new Collection<BookTag>(this);
// 要定义单向多对多,只需省略 `mappedBy`
@ManyToMany()
friends = new Collection<Author>(this);
}反向端
import { defineEntity, p } from '@mikro-orm/core';
const BookTagSchema = defineEntity({
name: 'BookTag',
properties: {
id: p.integer().primary(),
// 反向端必须通过 `mappedBy` 指向拥有方
books: () => p.manyToMany(Book).mappedBy('tags'),
},
});
export class BookTag extends BookTagSchema.class {}
BookTagSchema.setClass(BookTag);import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const BookTag = defineEntity({
name: 'BookTag',
properties: {
id: p.integer().primary(),
// 反向端必须通过 `mappedBy` 指向拥有方
books: () => p.manyToMany(Book).mappedBy('tags'),
},
});
export type IBookTag = InferEntity<typeof BookTag>;@Entity()
export class BookTag {
// 反向端必须通过 `mappedBy` 属性/参数指向拥有方
@ManyToMany(() => Book, book => book.tags)
books = new Collection<Book>(this);
}@Entity()
export class BookTag {
// 反向端必须通过 `mappedBy` 属性/参数指向拥有方
@ManyToMany(() => Book, book => book.tags)
books = new Collection<Book>(this);
}同样,关于集合如何工作的更多信息可以在集合页面找到。
通过另一个实体的 to-one 关系
有时,指向单个关联实体的链接并不是以外键的形式存储在拥有方表上。典型场景是:中间实体在携带链接的同时还带有额外列;或者你只想从一个 to-many 关系中暴露一项,比如最新的一项。两者都可以建模为带 through 选项的只读 ManyToOne 或 OneToOne 关系,它通过关联子查询而非外键列来解析目标。
through 实体需要一个指向拥有方实体的 ManyToOne 属性。当它与目标不同时,还需要一个指向目标实体的 ManyToOne 属性,这就是中间实体的情形。当 through 就是目标实体本身时,会直接选中它的主键,这正是你从一个 OneToMany 关系中挑出单项的方式。where 与 orderBy 选项作用于 through 实体,并取第一条匹配的行。
import { defineEntity, p } from '@mikro-orm/core';
const CustomerSchema = defineEntity({
name: 'Customer',
properties: {
id: p.integer().primary(),
edges: () => p.oneToMany(Edge).mappedBy('start'),
// 通过处于 `cleared` 状态的 edge 关联的账户
account: () => p.manyToOne(Account).through(() => Edge).where({ state: 'cleared' }).ref().nullable(),
// 该客户最新的 edge,从 `edges` 集合中挑出
latestEdge: () => p.oneToOne(Edge).through(() => Edge).orderBy({ id: 'desc' }).ref().nullable(),
},
});
export class Customer extends CustomerSchema.class {}
CustomerSchema.setClass(Customer);
const EdgeSchema = defineEntity({
name: 'Edge',
properties: {
id: p.integer().primary(),
start: () => p.manyToOne(Customer),
end: () => p.manyToOne(Account),
state: p.string(),
},
});
export class Edge extends EdgeSchema.class {}
EdgeSchema.setClass(Edge);import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const Customer = defineEntity({
name: 'Customer',
properties: {
id: p.integer().primary(),
edges: () => p.oneToMany(Edge).mappedBy('start'),
// 通过处于 `cleared` 状态的 edge 关联的账户
account: () => p.manyToOne(Account).through(() => Edge).where({ state: 'cleared' }).ref().nullable(),
// 该客户最新的 edge,从 `edges` 集合中挑出
latestEdge: () => p.oneToOne(Edge).through(() => Edge).orderBy({ id: 'desc' }).ref().nullable(),
},
});
export interface ICustomer extends InferEntity<typeof Customer> {}
export const Edge = defineEntity({
name: 'Edge',
properties: {
id: p.integer().primary(),
start: () => p.manyToOne(Customer),
end: () => p.manyToOne(Account),
state: p.string(),
},
});
export interface IEdge extends InferEntity<typeof Edge> {}@Entity()
export class Customer {
@PrimaryKey()
id!: number;
@OneToMany(() => Edge, e => e.start)
edges = new Collection<Edge>(this);
// 通过处于 `cleared` 状态的 edge 关联的账户
@ManyToOne(() => Account, { through: () => Edge, where: { state: 'cleared' }, ref: true, nullable: true })
account?: Ref<Account>;
// 该客户最新的 edge,从 `edges` 集合中挑出
@OneToOne(() => Edge, { through: () => Edge, orderBy: { id: 'desc' }, ref: true, nullable: true })
latestEdge?: Ref<Edge>;
}
@Entity()
export class Edge {
@PrimaryKey()
id!: number;
@ManyToOne(() => Customer)
start!: Customer;
@ManyToOne(() => Account)
end!: Account;
@Property()
state!: string;
}@Entity()
export class Customer {
@PrimaryKey()
id!: number;
@OneToMany(() => Edge, e => e.start)
edges = new Collection<Edge>(this);
// 通过处于 `cleared` 状态的 edge 关联的账户
@ManyToOne({ through: () => Edge, where: { state: 'cleared' }, ref: true, nullable: true })
account?: Ref<Account>;
// 该客户最新的 edge,从 `edges` 集合中挑出
@OneToOne({ through: () => Edge, orderBy: { id: 'desc' }, ref: true, nullable: true })
latestEdge?: Ref<Edge>;
}
@Entity()
export class Edge {
@PrimaryKey()
id!: number;
@ManyToOne()
start!: Customer;
@ManyToOne()
end!: Account;
@Property()
state!: string;
}在读取时,这类关系的行为与其他 to-one 关系一致:它可以用两种加载策略 populate,可以用于 where 与 orderBy 条件,可以与 ref 或 mapToPk 结合,并且参与 Loaded<> 类型推断与序列化。在底层,ORM 通过对 through 实体的子查询来选中目标主键。对于上面的 account 属性,子查询会经过中间实体:它按指回 customer 的外键以及 where 条件过滤 edge 行,并选中指向 account 的外键:
select c.*, (
select e.end_id from edge as e
where e.start_id = c.id and e.state = 'cleared'
limit 1
) as account_id from customer as clatestEdge 属性展示了另一种用法:through 就是目标实体本身,因此没有中间实体,子查询会直接选中 edge 的主键。它从 edges 集合本应包含的内容中挑出一行,用 orderBy 决定挑哪一行:
select c.*, (
select e.id from edge as e
where e.start_id = c.id
order by e.id desc
limit 1
) as latest_edge_id from customer as c这相当于加载 edges 集合并取最新的一项,但无需加载整个集合。把它与 where 结合,就能挑出例如处于某个给定状态的最新 edge。
该关系是只读的,不会为它创建列或外键约束,flush 期间对它的赋值会被忽略。要创建或修改这个链接,请直接操作 through 实体,例如通过像上面 edges 集合那样指向它的 OneToMany 关系。当有多行匹配时会取第一行,如果你需要保证最多只有一行,请在 through 实体上添加唯一索引。
where 与 orderBy 选项只能引用 through 实体自身的列。如果你需要针对关联实体的条件,请改用 formula 选项并自行编写子查询,through 选项只是它的快捷方式:
@ManyToOne(() => Account, {
formula: cols => `(select e.end_id from edge e join account a on a.id = e.end_id where e.start_id = ${cols.id} and e.state = 'cleared' and a.active = 1)`,
ref: true,
nullable: true,
})
account?: Ref<Account>;引用非主键列
默认情况下,ManyToOne 与 OneToOne 关系引用目标实体的主键。你可以使用 targetKey 选项改为引用另一个唯一列。
import { defineEntity, p } from '@mikro-orm/core';
const AuthorSchema = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
uuid: p.string().unique(),
books: () => p.oneToMany(Book).mappedBy('author'),
},
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
// 该关系通过 uuid 而非 id(主键)引用 Author
author: () => p.manyToOne(Author).targetKey('uuid'),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);import { defineEntity, InferEntity, p, Collection } from '@mikro-orm/core';
export const Author = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
uuid: p.string().unique(),
books: () => p.oneToMany(Book).mappedBy('author'),
},
});
export type IAuthor = InferEntity<typeof Author>;
export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
// 该关系通过 uuid 而非 id(主键)引用 Author
author: () => p.manyToOne(Author).targetKey('uuid'),
},
});
export type IBook = InferEntity<typeof Book>;@Entity()
export class Author {
@PrimaryKey()
id!: number;
@Property()
@Unique()
uuid!: string;
@OneToMany(() => Book, book => book.author)
books = new Collection<Book>(this);
}
@Entity()
export class Book {
@PrimaryKey()
id!: number;
// 该关系通过 uuid 而非 id(主键)引用 Author
@ManyToOne(() => Author, { targetKey: 'uuid' })
author!: Author;
}@Entity()
export class Author {
@PrimaryKey()
id!: number;
@Property()
@Unique()
uuid!: string;
@OneToMany(() => Book, book => book.author)
books = new Collection<Book>(this);
}
@Entity()
export class Book {
@PrimaryKey()
id!: number;
// 该关系通过 uuid 而非 id(主键)引用 Author
@ManyToOne({ targetKey: 'uuid' })
author!: Author;
}目标列必须有唯一约束。外键列的类型会自动与被引用列的类型保持一致。
ESM 项目中的关系
如果你在 TypeScript 项目中使用 ESM 搭配 reflect-metadata,可能会遇到循环依赖问题,看到类似这样的错误:
ReferenceError: Cannot access 'Author' before initialization要绕开它们,请使用 Rel 映射类型。它是一个恒等类型,会禁用来自 reflect-metadata 的那段有问题推断 —— 正是它导致 ESM 项目失败。
import { defineEntity, p } from '@mikro-orm/core';
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);使用
defineEntity时,循环依赖会被自动处理,无需Rel包装器。
import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author),
},
});
export type IBook = InferEntity<typeof Book>;使用
defineEntity时,循环依赖会被自动处理,无需Rel包装器。
import { Rel } from '@mikro-orm/core';
@Entity()
export class Book {
@ManyToOne(() => Author)
author!: Rel<Author>;
}import { Rel } from '@mikro-orm/core';
@Entity()
export class Book {
@ManyToOne()
author!: Rel<Author>;
}自定义外键约束名
如果你需要对底层 SQL schema 有更强的控制,可以在拥有方为关系的外键约束提供自定义名称。
该名称会覆盖当前命名策略自动生成的名称。
import { defineEntity, p } from '@mikro-orm/core';
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author).foreignKeyName('my_custom_name'),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author).foreignKeyName('my_custom_name'),
},
});
export type IBook = InferEntity<typeof Book>;@Entity()
export class Book {
@ManyToOne(() => Author, { foreignKeyName: 'my_custom_name' })
author: Author;
}@Entity()
export class Book {
@ManyToOne({ foreignKeyName: 'my_custom_name' })
author: Author;
}禁用外键约束创建
如果你需要为某个特定关系禁用底层 SQL 外键约束的创建,可以在拥有方把该关系的 createForeignKeyConstraint 设为 false。
import { defineEntity, p } from '@mikro-orm/core';
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author).createForeignKeyConstraint(false),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);import { defineEntity, InferEntity, p } from '@mikro-orm/core';
export const Book = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
author: () => p.manyToOne(Author).createForeignKeyConstraint(false),
},
});
export type IBook = InferEntity<typeof Book>;@Entity()
export class Book {
@ManyToOne(() => Author, { createForeignKeyConstraint: false })
author: Author;
}@Entity()
export class Book {
@ManyToOne({ createForeignKeyConstraint: false })
author: Author;
}注意,如果你通过把 createForeignKeyConstraints 设为 false 全局禁用了所有外键约束的创建,那么任何关系上都不会创建外键约束。
const orm = await MikroORM.init({
...
schemaGenerator: {
createForeignKeyConstraints: false,
},
});多态关系
多态关系允许一个属性引用多种不同类型的实体。当你的某个关系可以指向多种实体类型时,这很有用,比如一个"点赞"既可以关联到"文章"也可以关联到"评论"。
多态关系与单表继承(STI)不同:
- STI:多个实体类存储在同一张表中,共享一个公共基类。判别列标识要实例化哪个类。支持带引用完整性的原生外键约束。
- 多态关系:每种实体类型都有自己的表。判别列标识外键指向哪张表。无需继承。没有外键约束,因为该列可能指向多张表,也就没有数据库层面的引用完整性。
当实体共享公共字段与行为(继承)时使用 STI。当你需要无关实体类型之间的灵活关系时使用多态关系。
工作原理
多态关系在数据库中使用两列:
- 判别列 —— 存储实体类型(例如
'post'或'comment') - ID 列 —— 存储指向目标实体的外键值
与常规关系不同,多态关系不会创建外键约束,因为它们可以指向多张表。
定义多态关系
要定义多态关系,请向 @ManyToOne() 装饰器传入实体类型数组:
import { defineEntity, p } from '@mikro-orm/core';
const PostSchema = defineEntity({
name: 'Post',
properties: {
id: p.number().primary(),
title: p.string(),
// 多态关系的反向端
likes: () => p.oneToMany(UserLike).mappedBy('likeable'),
},
});
export class Post extends PostSchema.class {}
PostSchema.setClass(Post);
const CommentSchema = defineEntity({
name: 'Comment',
properties: {
id: p.number().primary(),
text: p.string(),
// 多态关系的反向端
likes: () => p.oneToMany(UserLike).mappedBy('likeable'),
},
});
export class Comment extends CommentSchema.class {}
CommentSchema.setClass(Comment);
const UserLikeSchema = defineEntity({
name: 'UserLike',
properties: {
id: p.number().primary(),
// 多态关系 —— 可以指向 Post 或 Comment
likeable: () => p.manyToOne([Post, Comment]),
},
});
export class UserLike extends UserLikeSchema.class {}
UserLikeSchema.setClass(UserLike);import { defineEntity, p, type InferEntity } from '@mikro-orm/core';
export const Post = defineEntity({
name: 'Post',
properties: {
id: p.number().primary(),
title: p.string(),
// 多态关系的反向端
likes: () => p.oneToMany(UserLike).mappedBy('likeable'),
},
});
export interface IPost extends InferEntity<typeof Post> {}
export const Comment = defineEntity({
name: 'Comment',
properties: {
id: p.number().primary(),
text: p.string(),
// 多态关系的反向端
likes: () => p.oneToMany(UserLike).mappedBy('likeable'),
},
});
export interface IComment extends InferEntity<typeof Comment> {}
export const UserLike = defineEntity({
name: 'UserLike',
properties: {
id: p.number().primary(),
// 多态关系 —— 可以指向 Post 或 Comment
likeable: () => p.manyToOne([Post, Comment]),
},
});
export interface IUserLike extends InferEntity<typeof UserLike> {}@Entity()
export class Post {
@PrimaryKey()
id!: number;
@Property()
title!: string;
// 多态关系的反向端
@OneToMany(() => UserLike, like => like.likeable)
likes = new Collection<UserLike>(this);
}
@Entity()
export class Comment {
@PrimaryKey()
id!: number;
@Property()
text!: string;
// 多态关系的反向端
@OneToMany(() => UserLike, like => like.likeable)
likes = new Collection<UserLike>(this);
}
@Entity()
export class UserLike {
@PrimaryKey()
id!: number;
// 多态关系 —— 可以指向 Post 或 Comment
@ManyToOne(() => [Post, Comment])
likeable!: Post | Comment;
}@Entity()
export class Post {
@PrimaryKey()
id!: number;
@Property()
title!: string;
@OneToMany(() => UserLike, like => like.likeable)
likes = new Collection<UserLike>(this);
}
@Entity()
export class Comment {
@PrimaryKey()
id!: number;
@Property()
text!: string;
@OneToMany(() => UserLike, like => like.likeable)
likes = new Collection<UserLike>(this);
}
@Entity()
export class UserLike {
@PrimaryKey()
id!: number;
// 类型被推断为 Post | Comment
@ManyToOne(() => [Post, Comment])
likeable!: Post | Comment;
}配置选项
discriminator 选项指定判别列所用的基础名称。实际列名由你的命名策略中的 discriminatorColumnName() 方法推导得出,默认会追加 Type 并转换为列格式(例如在 underscore 命名策略下,likeable 会变成 likeable_type)。
如果未指定,判别符默认为属性名(例如名为 likeable 的属性对应 likeable)。
数据库 Schema
对于上面的示例,user_like 表会有:
CREATE TABLE user_like (
id INTEGER PRIMARY KEY,
likeable_type VARCHAR(255), -- 判别列
likeable_id INTEGER -- 外键列
);注意不会创建外键约束,因为 likeable_id 既可能指向 post 表也可能指向 comment 表。
加载多态关系
加载带多态关系的实体时,MikroORM 会根据判别值自动确定正确的实体类型:
// 加载一个 UserLike 及其多态关系
const like = await orm.em.findOne(UserLike, { id: 1 });
// likeable 属性会是正确的实体类型
if (like.likeable instanceof Post) {
console.log('Liked a post:', like.likeable.title);
} else if (like.likeable instanceof Comment) {
console.log('Liked a comment:', like.likeable.text);
}加载反向端
反向端(OneToMany)集合与多态关系配合良好。populate 时,MikroORM 会自动过滤,只包含指向正确实体类型的元素:
// 加载一篇 Post 及其所有点赞
const post = await orm.em.findOne(Post, { id: 1 }, { populate: ['likes'] });
// 只包含指向该 post 的点赞
console.log('This post has', post.likes.length, 'likes');持久化多态关系
持久化时,MikroORM 会根据被赋值的实体类型自动设置判别值:
const post = new Post();
post.title = 'My Post';
const like = new UserLike();
like.likeable = post; // MikroORM 会设置 likeable_type = 'post'
orm.em.persist([post, like]);
await orm.em.flush();判别值
默认情况下,判别值是目标实体的表名。在上面的示例中:
- 指向
Post实体 → 判别值为'post' - 指向
Comment实体 → 判别值为'comment'
暴露判别列以便查询
判别列由 MikroORM 自动管理,但你可以把它暴露为只读属性以便查询。使用 persist: false 来阻止它被持久化(因为关系本身已经处理了这件事):
@Entity()
class UserLike {
@PrimaryKey()
id!: number;
// 暴露判别列以便查询(persist: false,因为它由关系管理)
@Property({ persist: false })
likeableType?: string;
@ManyToOne(() => [Post, Comment])
likeable!: Post | Comment;
}这允许你直接按判别值查询:
// 查找所有针对 post 的点赞
const postLikes = await orm.em.find(UserLike, {
likeableType: 'post',
});要求与限制
所有目标实体必须拥有兼容的主键类型 —— 由于同一个 ID 列要为所有目标类型存储外键,它们必须使用相同的类型(例如全部是整数主键或全部是字符串主键)。
没有外键约束 —— 多态关系无法拥有数据库层面的外键约束,因为它们指向多张表。
复合主键 —— 多态关系支持带复合主键的目标。会创建多个 ID 列来存储复合键的所有组成部分。
多对多多态关系
多态关系同样支持多对多关系。当你有一个像"标签"这样可被多种不同实体类型关联的共享关系时,这很有用(例如文章与视频都可以有标签)。
M:N 多态如何工作
与使用带两个外键的简单中间表的常规 M:N 关系不同,多态 M:N 使用带判别列的中间表来标识每一行属于哪种实体类型:
CREATE TABLE taggables (
taggable_type VARCHAR(255), -- 判别列:'post' 或 'video'
taggable_id INTEGER, -- 指向 post.id 或 video.id 的外键
tag_id INTEGER, -- 指向 tag.id 的外键
PRIMARY KEY (taggable_type, taggable_id, tag_id)
);多种实体类型共享同一张中间表,通过判别值区分。
定义 M:N 多态关系
要定义多态 M:N 关系,请在 @ManyToMany() 上使用 discriminator 选项:
import { defineEntity, p } from '@mikro-orm/core';
const TagSchema = defineEntity({
name: 'Tag',
properties: {
id: p.number().primary(),
name: p.string(),
// 反向端 —— 每种实体类型一个独立集合
posts: () => p.manyToMany(Post).mappedBy('tags'),
videos: () => p.manyToMany(Video).mappedBy('tags'),
},
});
export class Tag extends TagSchema.class {}
TagSchema.setClass(Tag);
const PostSchema = defineEntity({
name: 'Post',
properties: {
id: p.number().primary(),
title: p.string(),
// 拥有方 —— 通过共享中间表实现的多态 M:N
tags: () => p.manyToMany(Tag).pivotTable('taggables').discriminator('taggable'),
},
});
export class Post extends PostSchema.class {}
PostSchema.setClass(Post);
const VideoSchema = defineEntity({
name: 'Video',
properties: {
id: p.number().primary(),
url: p.string(),
// 拥有方 —— 同一张中间表,不同的判别值
tags: () => p.manyToMany(Tag).pivotTable('taggables').discriminator('taggable'),
},
});
export class Video extends VideoSchema.class {}
VideoSchema.setClass(Video);import { defineEntity, p, type InferEntity } from '@mikro-orm/core';
export const Tag = defineEntity({
name: 'Tag',
properties: {
id: p.number().primary(),
name: p.string(),
// 反向端 —— 每种实体类型一个独立集合
posts: () => p.manyToMany(Post).mappedBy('tags'),
videos: () => p.manyToMany(Video).mappedBy('tags'),
},
});
export interface ITag extends InferEntity<typeof Tag> {}
export const Post = defineEntity({
name: 'Post',
properties: {
id: p.number().primary(),
title: p.string(),
// 拥有方 —— 通过共享中间表实现的多态 M:N
tags: () => p.manyToMany(Tag).pivotTable('taggables').discriminator('taggable'),
},
});
export interface IPost extends InferEntity<typeof Post> {}
export const Video = defineEntity({
name: 'Video',
properties: {
id: p.number().primary(),
url: p.string(),
// 拥有方 —— 同一张中间表,不同的判别值
tags: () => p.manyToMany(Tag).pivotTable('taggables').discriminator('taggable'),
},
});
export interface IVideo extends InferEntity<typeof Video> {}@Entity()
export class Tag {
@PrimaryKey()
id!: number;
@Property()
name!: string;
// 反向端 —— 每种实体类型一个独立集合
@ManyToMany(() => Post, post => post.tags)
posts = new Collection<Post>(this);
@ManyToMany(() => Video, video => video.tags)
videos = new Collection<Video>(this);
}
@Entity()
export class Post {
@PrimaryKey()
id!: number;
@Property()
title!: string;
// 拥有方 —— 通过共享中间表实现的多态 M:N
@ManyToMany(() => Tag, tag => tag.posts, {
pivotTable: 'taggables',
discriminator: 'taggable',
owner: true,
})
tags = new Collection<Tag>(this);
}
@Entity()
export class Video {
@PrimaryKey()
id!: number;
@Property()
url!: string;
// 拥有方 —— 同一张中间表,不同的判别值
@ManyToMany(() => Tag, tag => tag.videos, {
pivotTable: 'taggables',
discriminator: 'taggable',
owner: true,
})
tags = new Collection<Tag>(this);
}@Entity()
export class Tag {
@PrimaryKey()
id!: number;
@Property()
name!: string;
@ManyToMany(() => Post, post => post.tags)
posts = new Collection<Post>(this);
@ManyToMany(() => Video, video => video.tags)
videos = new Collection<Video>(this);
}
@Entity()
export class Post {
@PrimaryKey()
id!: number;
@Property()
title!: string;
@ManyToMany(() => Tag, tag => tag.posts, {
pivotTable: 'taggables',
discriminator: 'taggable',
owner: true,
})
tags = new Collection<Tag>(this);
}
@Entity()
export class Video {
@PrimaryKey()
id!: number;
@Property()
url!: string;
@ManyToMany(() => Tag, tag => tag.videos, {
pivotTable: 'taggables',
discriminator: 'taggable',
owner: true,
})
tags = new Collection<Tag>(this);
}配置选项
| 选项 | 说明 |
|---|---|
pivotTable | 共享中间表的名称。所有使用同一判别符的多态实体都应使用相同的中间表名。 |
discriminator | 判别属性的名称。默认为属性名。列名由你的命名策略推导得出(例如 taggable → taggable_type)。 |
discriminatorMap | (可选)判别值到实体类的自定义映射。参见下方的自定义判别值。 |
owner | 在多态端必须为 true。 |
判别值
默认情况下,判别值是实体的表名:
Post实体 →'post'Video实体 →'video'
多态外键列名由判别属性名推导得出(例如 taggable → taggable_id)。
自定义判别值
你可以使用 discriminatorMap 选项指定自定义判别值。当你想使用更短或更有意义的类型标识时这很有用:
import { defineEntity, p } from '@mikro-orm/core';
const ArticleSchema = defineEntity({
name: 'Article',
properties: {
id: p.number().primary(),
categories: () => p.manyToMany(Category)
.inversedBy('articles')
.pivotTable('categorizables')
.discriminator('categorizable')
.discriminatorMap({ art: 'Article', prod: 'Product' })
.owner(),
},
});
export class Article extends ArticleSchema.class {}
ArticleSchema.setClass(Article);
const ProductSchema = defineEntity({
name: 'Product',
properties: {
id: p.number().primary(),
categories: () => p.manyToMany(Category)
.inversedBy('products')
.pivotTable('categorizables')
.discriminator('categorizable')
.discriminatorMap({ art: 'Article', prod: 'Product' })
.owner(),
},
});
export class Product extends ProductSchema.class {}
ProductSchema.setClass(Product);export const Article = defineEntity({
name: 'Article',
properties: {
id: p.number().primary(),
categories: () => p.manyToMany(Category)
.inversedBy('articles')
.pivotTable('categorizables')
.discriminator('categorizable')
.discriminatorMap({ art: 'Article', prod: 'Product' })
.owner(),
},
});
export const Product = defineEntity({
name: 'Product',
properties: {
id: p.number().primary(),
categories: () => p.manyToMany(Category)
.inversedBy('products')
.pivotTable('categorizables')
.discriminator('categorizable')
.discriminatorMap({ art: 'Article', prod: 'Product' })
.owner(),
},
});@Entity()
export class Article {
@PrimaryKey()
id!: number;
@ManyToMany(() => Category, cat => cat.articles, {
pivotTable: 'categorizables',
discriminator: 'categorizable',
discriminatorMap: {
art: 'Article', // 用 'art' 而非 'article'
prod: 'Product', // 用 'prod' 而非 'product'
},
owner: true,
})
categories = new Collection<Category>(this);
}
@Entity()
export class Product {
@PrimaryKey()
id!: number;
@ManyToMany(() => Category, cat => cat.products, {
pivotTable: 'categorizables',
discriminator: 'categorizable',
discriminatorMap: {
art: 'Article',
prod: 'Product',
},
owner: true,
})
categories = new Collection<Category>(this);
}在共享同一张中间表的所有实体上,discriminatorMap 的定义应当完全一致。值必须是实体类名(字符串)—— 由于 JavaScript 循环导入的限制,无法使用实体类引用。
使用 M:N 多态关系
// 创建带标签的实体
const tag1 = new Tag('TypeScript');
const tag2 = new Tag('Tutorial');
const post = new Post('Learning MikroORM');
post.tags.add(tag1, tag2);
const video = new Video('https://example.com/video.mp4');
video.tags.add(tag1); // 同一个标签可以被两者共用
await orm.em.persist([post, video]).flush();
// 加载并 populate 标签
const loadedPost = await orm.em.findOne(Post, post.id, { populate: ['tags'] });
console.log(loadedPost.tags.getItems()); // [Tag, Tag]
// 从反向端加载
const loadedTag = await orm.em.findOne(Tag, tag1.id, { populate: ['posts', 'videos'] });
console.log(loadedTag.posts.length); // 1
console.log(loadedTag.videos.length); // 1与常规 M:N 的差异
- 共享中间表 —— 多种实体类型共享同一张中间表,通过判别列区分。
- 多态端没有外键约束 —— 中间表无法在多态列上建立外键约束,因为它们指向不同的表。
- 独立的反向集合 —— 在反向端(Tag),你需要为每种实体类型提供独立集合(
posts、videos),或一个合并的反向集合。 - 相同的判别属性 —— 共享同一张中间表的所有实体必须使用相同的
discriminator属性名。
合并的反向集合
在 Rails 风格多态 M:N 的反向端,你可以不用按类型拆分的独立集合,而是声明一个把所有拥有方类型合并起来的联合集合:
@Entity()
class Tag {
// 按类型拆分的独立集合(始终可用)
@ManyToMany(() => Post, post => post.tags)
posts = new Collection<Post>(this);
@ManyToMany(() => Video, video => video.tags)
videos = new Collection<Video>(this);
// 合并的联合集合 —— 一次性加载所有拥有方类型
@ManyToMany(() => [Post, Video], 'tags')
owners = new Collection<Post | Video>(this);
}联合目标 M:N 多态关系
上一节讨论的是多个拥有方类型(Post、Video)共享一张中间表、指向单一目标(Tag)的情形 —— 判别符标识的是拥有方类型。镜像的形态同样受支持:单一拥有方持有一个包含多种目标类型的联合集合,此时判别符标识的是中间表每一行上的目标类型。
@Entity()
class Image {
@PrimaryKey()
id!: number;
@Property()
url!: string;
@ManyToMany(() => Post, post => post.attachments)
posts = new Collection<Post>(this);
}
@Entity()
class Video {
@PrimaryKey()
id!: number;
@Property()
src!: string;
@ManyToMany(() => Post, post => post.attachments)
posts = new Collection<Post>(this);
}
@Entity()
class Post {
@PrimaryKey()
id!: number;
@Property()
title!: string;
@ManyToMany({
entity: () => [Image, Video],
pivotTable: 'attachables',
discriminator: 'attachable',
owner: true,
})
attachments = new Collection<Image | Video>(this);
}@Entity()
class Image {
@PrimaryKey()
id!: number;
@Property()
url!: string;
@ManyToMany(() => Post, post => post.attachments)
posts = new Collection<Post>(this);
}
@Entity()
class Video {
@PrimaryKey()
id!: number;
@Property()
src!: string;
@ManyToMany(() => Post, post => post.attachments)
posts = new Collection<Post>(this);
}
@Entity()
class Post {
@PrimaryKey()
id!: number;
@Property()
title!: string;
@ManyToMany({
entity: () => [Image, Video],
pivotTable: 'attachables',
discriminator: 'attachable',
owner: true,
})
attachments = new Collection<Image | Video>(this);
}export const Image = defineEntity({
name: 'Image',
properties: {
id: p.number().primary(),
url: p.string(),
posts: () => p.manyToMany(Post).mappedBy('attachments'),
},
});
export const Video = defineEntity({
name: 'Video',
properties: {
id: p.number().primary(),
src: p.string(),
posts: () => p.manyToMany(Post).mappedBy('attachments'),
},
});
export const Post = defineEntity({
name: 'Post',
properties: {
id: p.number().primary(),
title: p.string(),
attachments: () => p.manyToMany([Image, Video])
.pivotTable('attachables')
.discriminator('attachable')
.owner(),
},
});中间表存储 (post_id, attachable_type, attachable_id) —— attachable_type 持有目标判别值('image' 或 'video'),attachable_id 指向对应目标表中的那一行。attachable_id 上没有外键约束,因为它跨越多张目标表。
CREATE TABLE attachables (
post_id INTEGER, -- 指向 post.id 的外键
attachable_type VARCHAR(255), -- 'image' 或 'video'
attachable_id INTEGER, -- 指向 image.id 或 video.id 的外键
PRIMARY KEY (post_id, attachable_type, attachable_id)
);像常规集合一样使用它 —— 你可以自由混用目标类型,加载回来的元素是正确具体类的实例:
const post = new Post();
post.attachments.add(new Image(), new Video());
await em.persist(post).flush();
const loaded = await em.findOneOrFail(Post, post.id, { populate: ['attachments'] });
for (const a of loaded.attachments) {
if (a instanceof Image) { /* ... */ }
if (a instanceof Video) { /* ... */ }
}反向端
每个目标实体都可以声明自己的反向集合指回拥有方。MikroORM 会自动按目标的判别值过滤共享中间表,因此 Image.posts 与 Video.posts 被干净地分离开:
const img = await em.findOneOrFail(Image, id, { populate: ['posts'] });
// img.posts 只包含该图片被附加到的 post —— 中间表会被自动
// 按 attachable_type='image' 过滤。注意事项
- 所有声明的目标必须拥有不同的
tableName,因为判别列是由tableName填充的。 - 联合目标 M:N 中集合元素的顺序反映中间表的顺序,并按目标类型分组。