---
title: 类型安全关系
---

来源：https://mikro-orm.io/docs/type-safe-relations

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

实体关系被映射为实体引用 —— 即至少拥有主键可用的实体实例。该引用被存放在标识映射中，因此从数据库取回同一个文档时你会得到相同的对象引用。

```ts
@ManyToOne(() => Author)
author!: Author;
```

这种方式的问题在于 TypeScript 无法知道该关系是否已加载。`author` 属性始终被类型化为 `Author`，即使它只是一个未初始化的引用。

```ts
const book = await em.findOne(Book, 1);
console.log(book.author instanceof Author); // true
console.log(wrap(book.author).isInitialized()); // false
console.log(book.author.name); // undefined —— Author 并未加载！
```

MikroORM 提供了若干工具来让关系的操作具备类型安全：

- **`Reference` 包装器** —— 包装关系以区分已加载与未加载状态
- **`Loaded` 类型** —— 在类型层面跟踪哪些关系已被 populate
- **`$` 访问器** —— 提供对已加载关系的类型安全同步访问

<a id="reference-wrapper"></a>
## `Reference` 包装器

`Reference` 包装器包裹一个实体引用，并提供安全访问它的方法：

- `load(): Promise<T>` —— 若实体尚未加载则加载它
- `unwrap(): T` —— 返回底层实体（不安全，可能未初始化）
- `isInitialized(): boolean` —— 检查实体是否已加载
- `getEntity(): T` —— 返回实体，未初始化时抛出异常
- `$` 或 `get()` —— 同步访问（仅在已加载时可用）

<a id="defining-references"></a>
### 定义引用

使用 `Ref<T>` 类型与 `ref: true` 选项来定义引用属性：

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

```ts title="./entities/Book.ts"
import { defineEntity, p } from '@mikro-orm/core';

const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    author: p.manyToOne(() => Author).ref(),
  },
});

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

  </TabItem>

<TabItem value="define-entity">

```ts title="./entities/Book.ts"
import { defineEntity, p } from '@mikro-orm/core';

export const Book = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    author: () => p.manyToOne(Author).ref(),
  },
});
```

</TabItem>
<TabItem value="reflect-metadata">

```ts title="./entities/Book.ts"
import { Ref, ref } from '@mikro-orm/core';
import { Entity, ManyToOne, PrimaryKey } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book {

  @PrimaryKey()
  id!: number;

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

  constructor(author: Author) {
    this.author = ref(author);
  }

}
```

</TabItem>
<TabItem value="ts-morph">

```ts title="./entities/Book.ts"
import { Ref, ref } from '@mikro-orm/core';
import { Entity, ManyToOne, PrimaryKey } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book {

  @PrimaryKey()
  id!: number;

  @ManyToOne()
  author: Ref<Author>;

  constructor(author: Author) {
    this.author = ref(author);
  }

}
```

</TabItem>
</Tabs>

<a id="using-references"></a>
### 使用引用

```ts
const book = await em.findOne(Book, 1);

// 引用尚未加载
book.author;                    // Ref<Author>
book.author.isInitialized();    // false
book.author.id;                 // OK —— 主键始终可用
book.author.name;               // TS 错误 —— Ref<Author> 上没有 'name'

// 加载该引用
const author = await book.author.load();
author.name;                    // OK —— 现在已加载

// 或者加载并访问特定属性
const name = await book.author.load('name');
```

当关系被 populate 时，你会得到 `LoadedReference`，它允许通过 `$` 同步访问：

```ts
const book = await em.findOne(Book, 1, { populate: ['author'] });

book.author;                    // LoadedReference<Author>
book.author.$.name;             // OK —— 类型安全的同步访问
book.author.get().name;         // 与上面相同，另一种写法
```

<a id="reference-methods"></a>
### 引用方法

| 方法 | 说明 |
|--------|-------------|
| `load()` | 加载实体，返回 `Promise<T>` |
| `load(prop)` | 加载实体并返回指定属性 |
| `unwrap()` | 返回底层实体（不安全） |
| `isInitialized()` | 实体已加载时返回 `true` |
| `getEntity()` | 返回实体，未初始化时抛出异常 |
| `getProperty(prop)` | 返回某个属性，未初始化时抛出异常 |
| `$` / `get()` | 同步访问（仅在 `LoadedReference` 上） |

```ts
const book = await em.findOne(Book, 1);

// 未初始化时这些会抛出异常
book.author.getEntity();           // Error: Reference<Author> not initialized
book.author.getProperty('name');   // Error: Reference<Author> not initialized

// 先加载，再同步访问
await book.author.load();
book.author.getEntity().name;      // OK
book.author.getProperty('name');   // OK
```

> 与总是从数据库刷新的 `wrap(entity).init()` 不同，`Reference.load()` 只会在实体不在标识映射中时才发起查询。

<a id="lazyreft--type-only-reference"></a>
## `LazyRef<T>` —— 纯类型引用

当你想要**编译期的 populate 状态安全性**，但又不想要 `Reference` 所要求的 `.$` / `.get()` 间接层时，请使用 `LazyRef<T>`。它是一个**纯类型**标记 —— 在运行时该属性直接持有实体实例（与不带 `ref: true` 的普通关系相同），但 TypeScript 会限制只能访问主键，直到 `Loaded<>` 收窄它为止。

```ts
@ManyToOne(() => Author)
author!: LazyRef<Author>;
```

或者配合 `defineEntity`：

```ts
const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    author: () => p.manyToOne(AuthorSchema).lazyRef(),
  },
});
```

<a id="semantics"></a>
### 语义

| | `LazyRef<T>` | `Ref<T>` |
|---|---|---|
| 运行时值 | 实体实例（桩或已水合） | `Reference` 包装器 |
| `instanceof T`（运行时） | `true` | `false` |
| 访问未加载的主键 | `ref.id` ✅ | `ref.id` ✅ |
| 访问未加载的非主键 | 编译错误 ✅ | 编译错误 ✅ |
| 访问已加载的属性 | `loaded.author.name`（无 `.$`） | `loaded.author.$.name` |
| `load()` / `loadOrFail()` 方法 | ❌ —— 请在目标上使用 `Loadable` mixin | ✅ 内置 |

> **关于 `instanceof` 的说明**：表格中的 `instanceof T` 一行说的是运行时 JS 检查 —— `book.author instanceof Author` 在运行时返回 `true`。然而 TypeScript 通过 `instanceof` 做的控制流收窄**不会**剥掉 `LazyRef<T>` 的品牌，因此 `if (book.author instanceof Author) { /* book.author.name 在这里依然是编译错误 */ }` 仍然无法给你完整的实体访问能力。请使用 `unref()` 或 `Loaded<>` 收窄来获得编译期访问。

<a id="usage"></a>
### 用法

```ts
const book = await em.findOneOrFail(Book, 1);
book.author.id;     // ok —— 主键始终可访问
book.author.name;   // 编译错误 —— 未加载

const loaded = await em.findOneOrFail(Book, 1, { populate: ['author'] });
loaded.author.name; // ok —— Loaded<Book, 'author'> 把 LazyRef<Author> 收窄为 Author
```

> **适用范围**：`LazyRef<T>` 仅用于 to-one 关系（`@ManyToOne`、`@OneToOne`）。集合已经通过 `Collection<T>` 拥有了自己的间接层。
>
> **注意**：这种安全性纯粹是编译期的。JS 代码、`as any` 强制转换，或绕过 `Loaded<>` 的代码路径都可以在运行时自由读取任何属性 —— 而在*未 populate* 的关系上（只设置了主键的桩），这些读取会返回 `undefined`。如果该关系已经被 populate，底层实体是完整水合的，读取行为正常；该注意事项只适用于桩的情形。这与普通的非 `Ref` 关系是同一个坑。
>
> **类型性能**：`LazyRef<T>` 在 `Loaded<>` / `AutoPath` 收窄路径中增加了一个条件分支。其开销与 `Ref<T>` 相当（事实上对已加载收窄而言略便宜，因为不会产生 `LoadedReference` 交叉类型）。测量数据参见 `tests/bench/types/lazy-ref.ts`。

<a id="unref--escape-hatch-when-you-cant-thread-loaded-through"></a>
### `unref()` —— 无法贯穿 `Loaded<>` 时的逃生舱

当你知道某个关系已被 populate，但周围代码的类型是裸 `Book` 而非 `Loaded<Book, 'author'>` 时，使用 `unref()` 把 `LazyRef<T>`（或 `Ref<T>`）收窄回 `T`。

```ts
import { unref } from '@mikro-orm/core';

function logAuthor(book: Book) {
  // `book.author` 是 `LazyRef<Author>` —— `.name` 会是编译错误
  console.log(unref(book.author).name);
}
```

`unref()` 是 `ref()` 的逆操作，适用于以下任意类型：

- `Ref<T>` / `Reference<T>`（实体）—— 调用 `.unwrap()`，返回 `T`
- `LazyRef<T>` —— 运行时为恒等转换（底层值已经是 `T`），返回 `T`
- 普通 `T` —— 直接透传，返回 `T`
- `ScalarReference<V>` / `ScalarRef<V>` —— 调用 `.unwrap()`，返回 `V | undefined`（标量可能未绑定）
- `null` / `undefined` —— 透传

与普通的 `as` 强制转换一样，`unref()` 只是编译期收窄，仅对实体关系有效 —— 如果该实体是一个从未被 populate 的桩，非主键属性在运行时依然是 `undefined`。在确信关系已加载时使用它；能贯穿 `Loaded<>` 时请优先这样做。

<a id="loadable-mixin--load--loadorfail-on-entities"></a>
## `Loadable` mixin —— 实体上的 `load()` / `loadOrFail()`

如果你使用普通关系或 `LazyRef<T>`，但又想要 `Reference` 在包装器上提供的那种 `load()` / `loadOrFail()` 使用体验，可以为你的实体类启用 `Loadable` mixin。它会把这两个方法加到实体原型上，于是你可以直接在关系目标上调用它们。

```ts
import { BaseEntity, Loadable, LoadableBaseEntity } from '@mikro-orm/core';

// 便捷方式：BaseEntity 已预先组合好该 mixin
class User extends LoadableBaseEntity {
  // ...
}

// 独立使用 —— 不继承基类
class Product extends Loadable() {
  // ...
}

// 或者与你自己的基类组合
class Article extends Loadable(MyBase) {
  // ...
}

const user = orm.em.getReference(User, 1);
const loaded = await user.load();          // Promise<User | null>
const loadedOrThrows = await user.loadOrFail(); // Promise<User>
```

按需启用是刻意设计：`BaseEntity` 本身**不会**获得这些方法，因此已存在 `load` / `loadOrFail` 属性的实体不受影响。

<a id="loaded-type"></a>
## `Loaded` 类型

`Loaded<Entity, Hints>` 类型在编译期跟踪哪些关系已被 populate。所有 `em.find*` 方法都返回该类型：

```ts
// 类型：Loaded<User, never>[]
const users = await em.find(User, {});

// 类型：Loaded<User, 'identity' | 'friends'>[]
const usersWithRelations = await em.find(User, {}, {
  populate: ['identity', 'friends'],
});
```

给定下面的 `User` 实体：

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

```ts title="./entities/User.ts"
import { defineEntity, p } from '@mikro-orm/core';

const UserSchema = defineEntity({
  name: 'User',
  properties: {
    id: p.integer().primary(),
    identity: p.manyToOne(() => Identity).ref(),
    friends: p.manyToMany(() => User),
  },
});

export class User extends UserSchema.class {}
UserSchema.setClass(User);
```

  </TabItem>

<TabItem value="define-entity">

```ts title="./entities/User.ts"
import { defineEntity, p } from '@mikro-orm/core';

export const User = defineEntity({
  name: 'User',
  properties: {
    id: p.integer().primary(),
    identity: () => p.manyToOne(Identity).ref(),
    friends: () => p.manyToMany(User),
  },
});
```

</TabItem>
<TabItem value="reflect-metadata">

```ts title="./entities/User.ts"
import { Collection, Ref, ref } from '@mikro-orm/core';
import { Entity, PrimaryKey, ManyToOne, ManyToMany } from '@mikro-orm/decorators/legacy';

@Entity()
export class User {

  @PrimaryKey()
  id!: number;

  @ManyToOne(() => Identity, { ref: true })
  identity: Ref<Identity>;

  @ManyToMany(() => User)
  friends = new Collection<User>(this);

  constructor(identity: Identity) {
    this.identity = ref(identity);
  }

}
```

</TabItem>
<TabItem value="ts-morph">

```ts title="./entities/User.ts"
import { Collection, Ref, ref } from '@mikro-orm/core';
import { Entity, PrimaryKey, ManyToOne, ManyToMany } from '@mikro-orm/decorators/legacy';

@Entity()
export class User {

  @PrimaryKey()
  id!: number;

  @ManyToOne()
  identity: Ref<Identity>;

  @ManyToMany(() => User)
  friends = new Collection<User>(this);

  constructor(identity: Identity) {
    this.identity = ref(identity);
  }

}
```

</TabItem>
</Tabs>

<a id="type-safe-access-with-"></a>
### 使用 `$` 进行类型安全访问

当某个关系出现在 `Loaded` 提示中时，你可以通过 `$` 符号同步访问它：

```ts
// 类型：Loaded<User, 'identity'>
const user = await em.findOneOrFail(User, 1, { populate: ['identity'] });

// 类型安全的同步访问
console.log(user.identity.$.email);
```

没有 populate 提示时，访问 `$` 会产生编译错误：

```ts
// 类型：Loaded<User, never>
const user = await em.findOneOrFail(User, 1);

// TS 错误：类型 'Ref<Identity>' 上不存在属性 '$'
console.log(user.identity.$.email);
```

> 如果你不喜欢 `$` 这类带魔力的符号名，可以使用 `get()` 方法，它是 `$` 的别名。

<a id="using-loaded-in-function-signatures"></a>
### 在函数签名中使用 `Loaded`

你可以在函数参数中要求关系已被 populate：

```ts
function sendWelcomeEmail(user: Loaded<User, 'identity'>) {
  // 类型安全 —— identity 保证已加载
  const email = user.identity.$.email;
  mailer.send(email, 'Welcome!');
}

// 可行 —— identity 已被 populate
const user1 = await em.findOneOrFail(User, 1, { populate: ['identity'] });
sendWelcomeEmail(user1);

// 编译错误 —— identity 未被 populate
const user2 = await em.findOneOrFail(User, 1);
sendWelcomeEmail(user2);
```

<a id="collections"></a>
### 集合

`$` 访问器同样适用于 `Collection`：

```ts
// 类型：Loaded<User, 'friends'>
const user = await em.findOneOrFail(User, 1, { populate: ['friends'] });

// 对已加载的集合进行类型安全的迭代
for (const friend of user.friends.$) {
  console.log(friend.email);
}
```

> 注意：`Loaded` 纯粹是编译期构造。你可以用类型断言绕过它，但这就违背了类型安全的初衷。

<a id="assigning-references"></a>
## 赋值引用

给 `Ref<T>` 属性赋值时，你需要把实体包装起来：

```ts
import { ref } from '@mikro-orm/core';

const book = await em.findOne(Book, 1);

// 使用 ref() 辅助函数
book.author = ref(someAuthor);

// 使用带 wrapped 选项的 getReference
book.author = em.getReference(Author, 2, { wrapped: true });

// 使用 toReference()
book.author = wrap(someAuthor).toReference();
```

> `ref(e)` 是 `wrap(e).toReference()` 的快捷方式，后者与 `Reference.create(e)` 等价。

<a id="creating-references-without-entitymanager"></a>
### 不借助 EntityManager 创建引用

你可以在实体构造函数中使用 `rel()` 创建引用：

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

```ts title="./entities/Book.ts"
import { defineEntity, p, rel } from '@mikro-orm/core';

const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    author: p.manyToOne(() => Author).ref(),
  },
});

// 用法：创建带 author 引用的 book
const book = em.create(Book, { author: rel(Author, authorId) });

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

  </TabItem>

<TabItem value="define-entity">

```ts title="./entities/Book.ts"
import { defineEntity, p, rel } from '@mikro-orm/core';

export const Book = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    author: () => p.manyToOne(Author).ref(),
  },
});

// 用法：创建带 author 引用的 book
const book = em.create(Book, { author: rel(Author, authorId) });
```

</TabItem>
<TabItem value="reflect-metadata">

```ts title="./entities/Book.ts"
import { Ref, rel } from '@mikro-orm/core';
import { Entity, ManyToOne, PrimaryKey } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book {

  @PrimaryKey()
  id!: number;

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

  constructor(authorId: number) {
    this.author = rel(Author, authorId);
  }

}
```

</TabItem>
<TabItem value="ts-morph">

```ts title="./entities/Book.ts"
import { Ref, rel } from '@mikro-orm/core';
import { Entity, ManyToOne, PrimaryKey } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book {

  @PrimaryKey()
  id!: number;

  @ManyToOne()
  author!: Ref<Author>;

  constructor(authorId: number) {
    this.author = rel(Author, authorId);
  }

}
```

</TabItem>
</Tabs>

另一种方式是使用 [`wrap()` 辅助函数](./16-wrap-helper.md)提供的 `toReference()` 方法：

```ts
const author = new Author(...);
book.author = wrap(author).toReference();
```

<a id="primary-key-access"></a>
## 主键访问

`Ref<T>` 类型包含实体的主键，允许无需加载即可直接访问：

```ts
const book = await em.findOne(Book, 1);
console.log(book.author.id); // OK —— 主键始终可用
```

MikroORM 会按 `_id`、`uuid`、`id` 的顺序检查来检测主键属性。对于自定义主键名，请使用 `PrimaryKeyProp` 符号：

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

```ts title="./entities/Author.ts"
import { defineEntity, p } from '@mikro-orm/core';

const AuthorSchema = defineEntity({
  name: 'Author',
  properties: {
    myPrimaryKey: p.integer().primary(),
  },
});

export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);

// 使用 defineEntity 时 PrimaryKeyProp 会被自动推断
```

  </TabItem>

<TabItem value="define-entity">

```ts title="./entities/Author.ts"
import { defineEntity, p, PrimaryKeyProp } from '@mikro-orm/core';

export const Author = defineEntity({
  name: 'Author',
  properties: {
    myPrimaryKey: p.integer().primary(),
  },
});

// 使用 defineEntity 时 PrimaryKeyProp 会被自动推断
```

</TabItem>
<TabItem value="reflect-metadata">

```ts title="./entities/Author.ts"
import { PrimaryKeyProp } from '@mikro-orm/core';
import { Entity, PrimaryKey } from '@mikro-orm/decorators/legacy';

@Entity()
export class Author {

  @PrimaryKey()
  myPrimaryKey!: number;

  [PrimaryKeyProp]?: 'myPrimaryKey';

}
```

</TabItem>
<TabItem value="ts-morph">

```ts title="./entities/Author.ts"
import { PrimaryKeyProp } from '@mikro-orm/core';
import { Entity, PrimaryKey } from '@mikro-orm/decorators/legacy';

@Entity()
export class Author {

  @PrimaryKey()
  myPrimaryKey!: number;

  [PrimaryKeyProp]?: 'myPrimaryKey';

}
```

</TabItem>
</Tabs>

```ts
// 现在自定义主键名也能工作
const book = await em.findOne(Book, 1);
console.log(book.author.myPrimaryKey);
```

对于 MongoDB，`id`（字符串）与 `_id`（ObjectId）都可用：

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

```ts title="./entities/Book.ts"
import { defineEntity, p } from '@mikro-orm/core';

const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    _id: p.type(ObjectId).primary(),
    id: p.string().serializedPrimaryKey(),
    author: p.manyToOne(() => Author).ref(),
  },
});

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

  </TabItem>

<TabItem value="define-entity">

```ts title="./entities/Book.ts"
import { defineEntity, p } from '@mikro-orm/core';

export const Book = defineEntity({
  name: 'Book',
  properties: {
    _id: p.type(ObjectId).primary(),
    id: p.string().serializedPrimaryKey(),
    author: () => p.manyToOne(Author).ref(),
  },
});
```

</TabItem>
<TabItem value="reflect-metadata">

```ts title="./entities/Book.ts"
import { Ref } from '@mikro-orm/core';
import { Entity, PrimaryKey, SerializedPrimaryKey, ManyToOne } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book {

  @PrimaryKey()
  _id!: ObjectId;

  @SerializedPrimaryKey()
  id!: string;

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

}
```

</TabItem>
<TabItem value="ts-morph">

```ts title="./entities/Book.ts"
import { Ref } from '@mikro-orm/core';
import { Entity, PrimaryKey, SerializedPrimaryKey, ManyToOne } from '@mikro-orm/decorators/legacy';

@Entity()
export class Book {

  @PrimaryKey()
  _id!: ObjectId;

  @SerializedPrimaryKey()
  id!: string;

  @ManyToOne()
  author!: Ref<Author>;

}
```

</TabItem>
</Tabs>

```ts
const book = await em.findOne(Book, 1);
console.log(book.author.id);  // string
console.log(book.author._id); // ObjectId
```

<a id="scalarreference-wrapper"></a>
## `ScalarReference` 包装器

对于惰性加载的标量属性（非关系），请使用 `ScalarRef<T>`：

```ts
@Property({ lazy: true, ref: true })
passwordHash!: Ref<string>;

@Property({ type: 'json', lazy: true, ref: true })
metadata!: ScalarRef<Record<string, unknown>>;
```

```ts
const user = await em.findOne(User, 1);

// 加载该惰性标量
const hash = await user.passwordHash.load();

// 或者 populate 它
const userWithHash = await em.findOne(User, 1, {
  populate: ['passwordHash'],
});
console.log(userWithHash.passwordHash.$);
```

> 对于 `string`、`number` 这类原始类型，`Ref<T>` 会自动解析为 `ScalarReference`。对于对象类型，请显式使用 `ScalarRef<T>`。

<a id="nullable-scalars"></a>
### 可空标量

当标量引用可空时，包装器始终为真值。请在加载之后检查实际值：

```ts
@Property({ type: 'json', nullable: true, lazy: true, ref: true })
config!: ScalarRef<Config | null>;
```

```ts
const entity = await em.findOne(Entity, 1, { populate: ['config'] });

// 包装器存在，但值可能为 null
if (entity.config.$) {
  // 可以安全使用
  console.log(entity.config.$.setting);
}
```
