---
title: 使用实体构造函数
---

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

在内部，`MikroORM` 从不对受管实体（那些通过 `EntityManager` 加载的实体）调用实体构造函数，因此你可以自由地按自己的意愿使用它。只有当你通过 `new` 运算符自己实例化类时（或使用 `em.create()` 创建新的实体实例时），构造函数才会被调用，所以它是创建新实体时强制要求数据的方便位置。

例如，下面这个 `Book` 实体定义会始终要求设置 `title` 与 `author`，但 `publisher` 是可选的：

```ts
@Entity()
export class Book {

  @PrimaryKey()
  id!: number;

  @Property()
  title: string;

  @Property()
  foo!: number;

  @ManyToOne()
  author: Author;

  @ManyToOne()
  publisher?: Publisher;

  @ManyToMany({ entity: () => BookTag, inversedBy: 'books' })
  tags = new Collection<BookTag>(this);

  constructor(title: string, author: Author) {
    this.title = title;
    this.author = author;
  }

}
```

现在你可以这样构造实体：

```ts
const author = new Author();
const book = new Book('Foo', author);
```

`em.create()` 也会自动检测并遵循构造函数参数：

```ts
const author = new Author();
const book = em.create(Book, { title: 'Foo', author, foo: 123 });
```

它会从数据中提取 `title` 与 `author` 并传给构造函数，只把其余部分（这里只有 `foo` 属性）赋值给创建出的实体。

> 构造函数参数的推断基于实体属性名。换句话说，你的参数名必须与实体属性名完全一致。

<a id="pojo-vs-entity-instance-in-constructor"></a>
## 构造函数中的 POJO 与实体实例

你可能会忍不住直接用一个 DTO 来定义构造函数：

```ts
constructor(dto: { title: string; author: number }) {
  this.title = dto.title;
  // 编译失败，`number` 不能赋值给 `Author`！
  this.author = dto.author;
}
```

如果你的 `dto.author` 是一个 POJO（是个对象，但不是 `Author` 实体的实例），会出现类似但更隐蔽的问题：它可能通过类型检查，但实际上同样无法工作。ORM 期望关联属性中是实体实例，别无其他。

不过不用担心，把主键转换成实体引用有个简单办法，就是 `rel()` 辅助函数：

```ts
@ManyToOne({ entity: () => Author })
author: Rel<Author>;

constructor(dto: { title: string; author: number }) {
  this.title = dto.title;
  this.author = rel(Author, dto.author);
}
```

`rel()` 辅助函数会创建一个尚未受管的实体实例（因为你没有传给它任何 `EntityManager` 实例），但一旦它变成受管状态，就会被视为已存在的实体引用。这实际上等价于 `em.getReference()`，只是手头不需要有 `EntityManager` 实例。

> `rel()` 是 `Reference.createNakedFromPK()` 的简写。

如果你想更安全一些、使用 `Reference` 包装器，`ref()` 辅助函数也接受这个新签名：

```ts
@ManyToOne({ entity: () => Author, ref: true })
author: Ref<Author>;

constructor(dto: { title: string; author: number }) {
  this.title = dto.title;
  this.author = ref(Author, dto.author);
}
```

或者，为了让运行时保持为普通实体（无包装器）同时仍获得编译期的填充状态安全，请把属性声明为 [`LazyRef<T>`](./20-type-safe-relations.md#lazyreft--type-only-reference) 并用 `rel()` 赋值：

```ts
@ManyToOne({ entity: () => Author })
author: LazyRef<Author>;

constructor(dto: { title: string; author: number }) {
  this.title = dto.title;
  this.author = rel(Author, dto.author);
}
```

`rel` 与 `ref` 辅助函数既接受主键也接受实体实例，还接受空值（`null` 或 `undefined`）。

```ts
book.author = ref(Author, null);
book.author = ref(Author, undefined);
book.author = ref(null);
book.author = ref(undefined);
book.author = ref(Author, 1);
book.author = ref(Author, author);
book.author = ref(author);
```

<a id="property-initializers-with-defineentity-and-extends"></a>
## `defineEntity` 与 `extends` 下的属性初始化器

把 `defineEntity` 与 `extends` 选项一起使用时，基类的属性初始化器会被继承，并通过 `super()` 自动运行。这让你可以在基类上定义 `id = v4()` 或 `createdAt = new Date()` 这样的默认值，并让它们在所有通过 `new` 创建的子实体中生效。完整示例参见[通过 `extends` 复用基础属性](./61-define-entity.md#extends-initializers)。

<a id="using-native-private-properties"></a>
## 使用原生私有属性

如果你想在实体内部使用原生私有属性，MikroORM 通过 `Object.create()` 创建实体实例的默认做法就不可行了（更多内容见这个[issue](https://github.com/mikro-orm/mikro-orm/issues/1226)）。要强制使用实体构造函数，可以打开 [`forceEntityConstructor`](./58-configuration.md#using-native-private-properties) 开关。
