---
title: 用 defineEntity 定义实体
---

来源：https://mikro-orm.io/docs/define-entity

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

`defineEntity` 辅助函数是不使用装饰器、以编程方式定义实体的推荐做法。它构建在 `EntitySchema` 之上，利用 TypeScript 的类型推断自动生成实体类型。

<a id="defineentity"></a>
## `defineEntity`

用 `defineEntity` 来声明你的实体。它会返回一个带有完整类型信息的 `EntitySchema` 实例。

```ts
import { defineEntity, p } from '@mikro-orm/core';

const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    title: p.string(),
    author: () => p.manyToOne(Author).inversedBy('books'),
    tags: () => p.manyToMany(BookTag).inversedBy('books').fixedOrder(),
  },
});

export class Book extends BookSchema.class {}
BookSchema.setClass(Book);
```

`p` 这个简写也可以通过 `defineEntity.properties` 取得。

<a id="the-defineentity--class-pattern-recommended"></a>
### `defineEntity + class` 模式（推荐）

当你继承自动生成的类并通过 `setClass()` 注册它时，会得到几项好处：

- **悬停类型干净**：把鼠标悬停在 `Book` 变量上显示的是 `Book`，而不是带泛型和符号的复杂交叉类型
- **性能更好**：真实的具名类比纯方案中动态生成的匿名类更高效
- **自定义方法**：可以直接在实体实例上添加领域逻辑，无需任何变通
- **属性不重复**：属性只在 schema 中定义一次，类会自动继承它们

```ts
const AuthorSchema = defineEntity({
  name: 'Author',
  properties: {
    id: p.integer().primary(),
    firstName: p.string(),
    lastName: p.string(),
    books: () => p.oneToMany(Book).mappedBy('author'),
  },
});

class Author extends AuthorSchema.class {
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

AuthorSchema.setClass(Author);

// 用法：
const author = em.create(Author, { firstName: 'John', lastName: 'Doe' });
console.log(author.fullName()); // "John Doe"
```

> **重要：** `setClass()` 必须在 ORM 的发现流程运行之前调用（即在 `MikroORM.init()` 之前）。请确保在模块加载时、定义完扩展类之后立刻调用它。

<a id="pure-defineentity-without-a-class"></a>
### 纯 `defineEntity`（不带类）

你也可以不继承类而直接使用 `defineEntity`。对于简单实体，这样更紧凑，但悬停时会得到复杂的计算类型。

```ts
import { type InferEntity, defineEntity, p } from '@mikro-orm/core';

export const Book = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    title: p.string(),
    author: () => p.manyToOne(Author).inversedBy('books'),
    tags: () => p.manyToMany(BookTag).inversedBy('books').fixedOrder(),
  },
});

// 用 InferEntity 提取实体类型
export type IBook = InferEntity<typeof Book>;
```

在没有类的情况下创建新实体实例时，请使用 `em.create()`，它会创建内部生成的类的实例：

```ts
const book = em.create(Book, { title: 'My Book', author });
await em.flush();
```

<a id="reusing-base-properties"></a>
### 复用基础属性

用 `defineEntity` 在多个实体间共享公共属性有两种方式：

<a id="via-composition-shared-property-objects"></a>
#### 通过组合（共享属性对象）

最简单的办法——把一个共享的属性对象展开到每个实体的 properties 中：

```ts
const p = defineEntity.properties;

const baseProperties = {
  id: p.integer().primary(),
  createdAt: p.datetime().onCreate(() => new Date()),
  updatedAt: p.datetime()
    .onCreate(() => new Date())
    .onUpdate(() => new Date()),
};

const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    ...baseProperties,
    title: p.string(),
    author: () => p.manyToOne(Author),
  },
});

export class Book extends BookSchema.class {}
BookSchema.setClass(Book);
```

<a id="extends-initializers"></a>
#### 通过 `extends` 配合属性初始化器 {#extends-initializers}

当使用 `defineEntity + class` 模式并配合 `extends` 时，自动生成的类在 JavaScript 层面会继承父类。这意味着定义在基类上的属性初始化器（如 `id = v4()` 或 `createdAt = new Date()`）会在通过 `new` 构造子实体时自动执行：

```ts
const BaseSchema = defineEntity({
  name: 'BaseEntity',
  abstract: true,
  properties: {
    id: p.string().primary(),
    createdAt: p.datetime(),
    updatedAt: p.datetime(),
  },
});

export class Base extends BaseSchema.class {
  id = v4();
  createdAt = new Date();
  updatedAt = new Date();
}

BaseSchema.setClass(Base);

const UserSchema = defineEntity({
  name: 'User',
  extends: BaseSchema,
  properties: {
    email: p.string().unique(),
    name: p.string(),
  },
});

export class User extends UserSchema.class {
  name = '';
}

UserSchema.setClass(User);

// id、createdAt、updatedAt 由 Base 的属性初始化器完成初始化
const user = new User();
console.log(user.id); // 一个 UUID 字符串
console.log(user.createdAt); // 当前 Date
```

> 当你需要不依赖 `EntityManager` 上下文（即直接 `new`）也能生效的构造期默认值时，这种方式很有用。如果你只需要在持久化期间设置默认值，可以改用 `onCreate` 钩子——详见[映射超类](./21-inheritance-mapping.md#mapped-superclasses)。

<a id="extends-methods"></a>
#### 继承基类方法 {#extends-methods}

声明在基类上的方法**在运行时**总是会被继承——自动生成的子类继承自基类，因此子实例是基类的 `instanceof`，也能调用它的方法。但在**类型层面**，`extends: BaseSchema` 只携带映射的属性；TypeScript 看不到你之后通过 `setClass` 挂到 schema 上的方法。要让这些方法在子实体类型上可见，请让 `extends` 指向基**类**而不是 schema：

```ts
export class Base extends BaseSchema.class {
  id = v4();
  createdAt = new Date();
  updatedAt = new Date();

  wasUpdated(): boolean {
    return this.updatedAt > this.createdAt;
  }
}

BaseSchema.setClass(Base);

const UserSchema = defineEntity({
  name: 'User',
  extends: Base, // 传类而不是 BaseSchema——让 `wasUpdated()` 出现在子类型上
  properties: {
    email: p.string().unique(),
  },
});

export class User extends UserSchema.class {
  describe() {
    return this.wasUpdated() ? `${this.email} (edited)` : this.email;
  }
}

UserSchema.setClass(User);
```

两种写法在运行时行为完全一致；传类只是让 TypeScript 能传递继承来的方法签名。继承 schema（`extends: BaseSchema`）仍然会继承所有映射属性，当基类只贡献列时它是正确的选择。

<a id="property-types"></a>
### 属性类型

`defineEntity.properties`（别名 `p`）提供了所有 [MikroORM 内置类型](./26-custom-types.md#types-provided-by-mikroorm)。要使用[自定义类型](./26-custom-types.md)，请用 `p.type()`：

```ts
const properties = {
  string: p.string(),
  float: p.float(),
  boolean: p.boolean(),
  json: p.json<{ foo: string; bar: number }>().nullable(),
  stringArray: p.type(ArrayType<string>).nullable(),
  numericArray: p.type(new ArrayType(i => +i)).nullable(),
  point: p.type(PointType).nullable(),
};
```

<a id="relation-modifiers-ref-and-lazyref"></a>
### 关联修饰器：`.ref()` 与 `.lazyRef()`

对于 `m:1` / `1:1` 关联，你可以选择启用编译期的填充状态安全：

- **`.ref()`** 会把运行时值包进一个 `Reference`，对外暴露 `.$` / `.get()` / `.load()`——参见 [`Ref<T>`](./20-type-safe-relations.md#reference-wrapper)。
- **`.lazyRef()`** 是纯类型层面的标记——运行时仍是普通实体（没有包装器），但 TypeScript 会隐藏非主键的访问，直到 `Loaded<>` 收窄它。参见 [`LazyRef<T>`](./20-type-safe-relations.md#lazyreft--type-only-reference)。

```ts
const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    author: () => p.manyToOne(AuthorSchema).ref(),       // `Ref<Author>`
    publisher: () => p.manyToOne(PublisherSchema).lazyRef(), // `LazyRef<Publisher>`
  },
});
```

<a id="mongodb-example"></a>
## MongoDB 示例

<Tabs
  groupId="entity-schema-def"
  defaultValue="define-entity-class"
  values={[
    {label: 'defineEntity + class', value: 'define-entity-class'},
    {label: 'defineEntity', value: 'define-entity'},
  ]}
>
  <TabItem value="define-entity-class">

```ts
const BookTagSchema = defineEntity({
  name: 'BookTag',
  properties: {
    _id: p.type(ObjectId).primary(),
    id: p.string().serializedPrimaryKey(),
    name: p.string(),
    books: () => p.manyToMany(Book).mappedBy('tags'),
  },
});

export class BookTag extends BookTagSchema.class {}
BookTagSchema.setClass(BookTag);
```

  </TabItem>

  <TabItem value="define-entity">

```ts
export const BookTag = defineEntity({
  name: 'BookTag',
  properties: {
    _id: p.type(ObjectId).primary(),
    id: p.string().serializedPrimaryKey(),
    name: p.string(),
    books: () => p.manyToMany(Book).mappedBy('tags'),
  },
});

export type IBookTag = InferEntity<typeof BookTag>;
```

  </TabItem>
</Tabs>

<a id="hooks-example"></a>
## 钩子示例

钩子有两种注册方式：

- **`hooks` 属性**——在 `defineEntity` 调用中直接传入一个由钩子处理函数数组构成的对象。
- **`addHook` 方法**——在实体定义完成之后再注册钩子处理函数。

两种方式都接受函数（箭头函数、具名函数、async 函数）。实体实例可通过 `args.entity` 取得。可用钩子的完整列表与 `EventArgs` 细节参见[事件与生命周期钩子](./48-events.md)。

<Tabs
  groupId="entity-schema-hooks"
  defaultValue="define-entity-class"
  values={[
    {label: 'defineEntity + class', value: 'define-entity-class'},
    {label: 'defineEntity', value: 'define-entity'},
  ]}
>
  <TabItem value="define-entity-class">

在类定义完成后使用 `addHook`，以获得完整的类型安全：

```ts
const BookTagSchema = defineEntity({
  name: 'BookTag',
  properties: {
    _id: p.type(ObjectId).primary(),
    id: p.string().serializedPrimaryKey(),
    name: p.string(),
    version: p.integer(),
    books: () => p.manyToMany(Book).mappedBy('tags'),
  },
});

export class BookTag extends BookTagSchema.class {}
BookTagSchema.setClass(BookTag);

// highlight-start
BookTagSchema.addHook('beforeCreate', (args: EventArgs<BookTag>) => {
  args.entity.version = 1;
});

BookTagSchema.addHook('beforeUpdate', (args: EventArgs<BookTag>) => {
  args.entity.version++;
});
// highlight-end
```

> 你也可以通过 `hooks` 属性内联传入钩子，但那里 `args.entity` 的类型会是 `any`，因为此时实体类型尚未可知。显式标注参数类型（例如 `EventArgs<BookTag>`）也行不通，因为那会形成循环引用。要获得完整的类型安全，请在类定义完成之后使用 `addHook`。

  </TabItem>

  <TabItem value="define-entity">

在实体定义完成后使用 `addHook`，以获得完整的类型安全：

```ts
export const BookTag = defineEntity({
  name: 'BookTag',
  properties: {
    _id: p.type(ObjectId).primary(),
    id: p.string().serializedPrimaryKey(),
    name: p.string(),
    version: p.integer(),
    books: () => p.manyToMany(Book).mappedBy('tags'),
  },
});

export type IBookTag = InferEntity<typeof BookTag>;

// highlight-start
BookTag.addHook('beforeCreate', (args: EventArgs<IBookTag>) => {
  args.entity.version = 1;
});

BookTag.addHook('beforeUpdate', (args: EventArgs<IBookTag>) => {
  args.entity.version++;
});
// highlight-end
```

> 你也可以通过 `hooks` 属性内联传入钩子，但那里 `args.entity` 的类型会是 `any`，因为此时实体类型尚未可知。显式标注参数类型（例如 `EventArgs<IBookTag>`）也行不通，因为那会形成循环引用。要获得完整的类型安全，请在实体及其类型别名定义完成之后使用 `addHook`。

  </TabItem>
</Tabs>

<a id="entityschema-low-level-api"></a>
## `EntitySchema`（底层 API）

`defineEntity` 返回一个 `EntitySchema` 实例——也就是你可以直接实例化的同一个类。通常没必要直接使用 `EntitySchema`，因为 `defineEntity` 提供了更符合人体工学、且具备完整类型推断的 API。不过在高级场景或原生 JavaScript 项目中，它仍然可用。

```ts title="./entities/Book.ts"
export interface IBook {
  title: string;
  author: Author;
  publisher: Publisher;
  tags: Collection<BookTag>;
}

export const BookSchema = new EntitySchema<IBook>({
  name: 'Book',
  extends: CustomBaseEntitySchema,
  properties: {
    title: { type: 'string' },
    author: { kind: 'm:1', entity: () => Author, inversedBy: 'books' },
    publisher: { kind: 'm:1', entity: () => Publisher, inversedBy: 'books' },
    tags: { kind: 'm:n', entity: () => BookTag, inversedBy: 'books', fixedOrder: true },
  },
});
```

<a id="using-a-class-with-entityschema"></a>
### 搭配 `EntitySchema` 使用类

你可以传入 `class` 选项来代替 `name`：

```ts title="./entities/Author.ts"
export class Author extends CustomBaseEntity {
  name: string;
  email: string;

  constructor(name: string, email: string) {
    super();
    this.name = name;
    this.email = email;
  }
}

export const AuthorSchema = new EntitySchema({
  class: Author,
  extends: CustomBaseEntitySchema,
  properties: {
    name: { type: 'string' },
    email: { type: 'string', unique: true },
  },
});
```

<a id="configuration-reference"></a>
### 配置参考

`EntitySchema` 的参数要求 `name` 或 `class` 二者之一。使用 `class` 时，`extends` 会被自动推断。其他参数：

```ts
name: string;
class: Constructor<T>;
extends: string;
tableName: string; // `collection: string` 的别名
properties: { [K in keyof T & string]: EntityProperty<T[K]> };
indexes: { properties: string | string[]; name?: string; type?: string }[];
uniques: { properties: string | string[]; name?: string }[];
repository: () => Constructor<EntityRepository<T>>;
hooks: Partial<Record<keyof typeof EventType, ((string & keyof T) | NonNullable<EventSubscriber[keyof EventSubscriber]>)[]>>;
abstract: boolean;
orderBy: QueryOrderMap<T> | QueryOrderMap<T>[]; // 实体的默认排序
```

> `type` 的取值也可以使用 `String`/`Number`/`Boolean`/`Date` 之一。
