# 快速开始

> 英文标题：Getting Started
> 官网原文：https://typeorm.io/docs/getting-started
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 184 块

---

<!-- EN -->
# Getting Started

<!-- ZH -->
# 快速开始

<!-- EN -->
TypeORM is an [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) that can run in Node.js, Browser, Cordova, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES2023).

<!-- ZH -->
TypeORM 是一个 [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)，可运行在 Node.js、Browser、Cordova、Ionic、React Native、NativeScript、Expo 和 Electron 平台上，并可与 TypeScript 和 JavaScript（ES2023）一起使用。

<!-- EN -->
Its goal is to always support the latest JavaScript features and provide additional features that help you to develop any kind of application that uses databases - from small applications with a few tables to large-scale enterprise applications with multiple databases.

<!-- ZH -->
它的目标是始终支持最新的 JavaScript 特性，并提供额外的能力，帮助你开发任何类型的数据库应用——从只有几张表的小型应用，到使用多个数据库的大型企业级应用。

<!-- EN -->
TypeORM supports more databases than any other JS/TS ORM: [Google Spanner](https://typeorm.io/docs/drivers/google-spanner), [Microsoft SqlServer](https://typeorm.io/docs/drivers/microsoft-sqlserver), [MongoDB](https://typeorm.io/docs/drivers/mongodb), [MySQL/MariaDB](https://typeorm.io/docs/drivers/mysql), [Oracle](https://typeorm.io/docs/drivers/oracle), [Postgres](https://typeorm.io/docs/drivers/postgres), [SAP HANA](https://typeorm.io/docs/drivers/sap) and [SQLite](https://typeorm.io/docs/drivers/sqlite), as well as derived databases and different drivers.

<!-- ZH -->
TypeORM 支持的数据库比任何其他 JS/TS ORM 都多：[Google Spanner](https://typeorm.io/docs/drivers/google-spanner)、[Microsoft SqlServer](https://typeorm.io/docs/drivers/microsoft-sqlserver)、[MongoDB](https://typeorm.io/docs/drivers/mongodb)、[MySQL/MariaDB](https://typeorm.io/docs/drivers/mysql)、[Oracle](https://typeorm.io/docs/drivers/oracle)、[Postgres](https://typeorm.io/docs/drivers/postgres)、[SAP HANA](https://typeorm.io/docs/drivers/sap) 和 [SQLite](https://typeorm.io/docs/drivers/sqlite)，以及各类衍生数据库与不同驱动。

<!-- EN -->
TypeORM supports both [Active Record](https://typeorm.io/docs/guides/active-record-data-mapper#what-is-the-active-record-pattern) and [Data Mapper](https://typeorm.io/docs/guides/active-record-data-mapper#what-is-the-data-mapper-pattern) patterns, unlike all other JavaScript ORMs currently in existence, which means you can write high-quality, loosely coupled, scalable, maintainable applications in the most productive way.

<!-- ZH -->
与目前存在的所有其他 JavaScript ORM 不同，TypeORM 同时支持 [Active Record](https://typeorm.io/docs/guides/active-record-data-mapper#what-is-the-active-record-pattern) 和 [Data Mapper](https://typeorm.io/docs/guides/active-record-data-mapper#what-is-the-data-mapper-pattern) 两种模式，这意味着你可以用最高的效率编写高质量、松耦合、可扩展、易维护的应用。

<!-- EN -->
TypeORM is highly influenced by other ORMs, such as [Hibernate](http://hibernate.org/orm/), [Doctrine](http://www.doctrine-project.org/) and [Entity Framework](https://www.asp.net/entity-framework).

<!-- ZH -->
TypeORM 深受其他 ORM 的影响，例如 [Hibernate](http://hibernate.org/orm/)、[Doctrine](http://www.doctrine-project.org/) 和 [Entity Framework](https://www.asp.net/entity-framework)。

<!-- EN -->
## Features

<!-- ZH -->
## 特性

<!-- EN -->
* Supports both [DataMapper](https://typeorm.io/docs/guides/active-record-data-mapper#what-is-the-data-mapper-pattern) and [ActiveRecord](https://typeorm.io/docs/guides/active-record-data-mapper#what-is-the-active-record-pattern) (your choice).
* Entities and columns.
* Database-specific column types.
* Entity manager.
* Repositories and custom repositories.
* Clean object-relational model.
* Associations (relations).
* Eager and lazy relations.
* Unidirectional, bidirectional, and self-referenced relations.
* Supports multiple inheritance patterns.
* Cascades.
* Indexes.
* Transactions.
* [Migrations](https://typeorm.io/docs/migrations/why) with automatic generation.
* Connection pooling.
* Replication.
* Using multiple database instances.
* Working with multiple database types.
* Cross-database and cross-schema queries.
* Elegant-syntax, flexible and powerful QueryBuilder.
* Left and inner joins.
* Proper pagination for queries using joins.
* Query caching.
* Streaming raw results.
* Logging.
* Listeners and subscribers (hooks).
* Supports closure table pattern.
* Schema declaration in models or separate configuration files.
* Supports MySQL / MariaDB / Postgres / CockroachDB / SQLite / Microsoft SQL Server / Oracle / SAP Hana / sql.js.
* Supports MongoDB NoSQL database.
* Works in Node.js / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron platforms.
* TypeScript and JavaScript support.
* ESM and CommonJS support.
* Produced code is performant, flexible, clean, and maintainable.
* Follows all possible best practices.
* CLI.

<!-- ZH -->
* 同时支持 [DataMapper](https://typeorm.io/docs/guides/active-record-data-mapper#what-is-the-data-mapper-pattern) 与 [ActiveRecord](https://typeorm.io/docs/guides/active-record-data-mapper#what-is-the-active-record-pattern)（由你选择）。
* 实体与列。
* 数据库专属的列类型。
* Entity Manager。
* Repository 与自定义仓储。
* 清晰的对象关系模型。
* 关联（关系）。
* 急加载与懒加载关系。
* 单向、双向与自引用关系。
* 支持多种继承模式。
* 级联。
* 索引。
* 事务。
* 支持自动生成的[迁移](https://typeorm.io/docs/migrations/why)。
* 连接池。
* 复制。
* 使用多个数据库实例。
* 同时使用多种数据库类型。
* 跨数据库与跨模式查询。
* 语法优雅、灵活而强大的 QueryBuilder。
* 左连接与内连接。
* 针对使用连接的查询提供合理的分页。
* 查询缓存。
* 流式处理原生结果。
* 日志。
* 监听器与订阅者（钩子）。
* 支持闭包表（closure table）模式。
* 可在模型中声明结构，也可使用独立配置文件。
* 支持 MySQL / MariaDB / Postgres / CockroachDB / SQLite / Microsoft SQL Server / Oracle / SAP Hana / sql.js。
* 支持 MongoDB NoSQL 数据库。
* 可运行在 Node.js / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron 平台。
* 支持 TypeScript 与 JavaScript。
* 支持 ESM 与 CommonJS。
* 产出的代码高性能、灵活、清晰且易维护。
* 遵循一切可能的最佳实践。
* CLI。

<!-- EN -->
And more...

<!-- ZH -->
还有更多……

<!-- EN -->
With TypeORM, your models look like this:

<!-- ZH -->
使用 TypeORM 时，你的模型长这样：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}
```

<!-- EN -->
And your domain logic looks like this:

<!-- ZH -->
你的领域逻辑长这样：

<!-- EN -->
```typescript
const userRepository = AppDataSource.getRepository(User)

const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.age = 25
await userRepository.save(user)

const allUsers = await userRepository.find()
const firstUser = await userRepository.findOneBy({
    id: 1,
}) // find by id
const timber = await userRepository.findOneBy({
    firstName: "Timber",
    lastName: "Saw",
}) // find by firstName and lastName

await userRepository.remove(timber)
```

<!-- ZH -->
```typescript
const userRepository = AppDataSource.getRepository(User)

const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.age = 25
await userRepository.save(user)

const allUsers = await userRepository.find()
const firstUser = await userRepository.findOneBy({
    id: 1,
}) // 按 id 查找
const timber = await userRepository.findOneBy({
    firstName: "Timber",
    lastName: "Saw",
}) // 按 firstName 和 lastName 查找

await userRepository.remove(timber)
```

<!-- EN -->
Alternatively, if you prefer to use the `ActiveRecord` implementation, you can use it as well:

<!-- ZH -->
或者，如果你更倾向于使用 `ActiveRecord` 实现，也可以这样用：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm"

@Entity()
export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm"

@Entity()
export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}
```

<!-- EN -->
And your domain logic will look this way:

<!-- ZH -->
此时你的领域逻辑会变成这样：

<!-- EN -->
```typescript
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.age = 25
await user.save()

const allUsers = await User.find()
const firstUser = await User.findOneBy({
    id: 1,
})
const timber = await User.findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})

await timber.remove()
```

<!-- ZH -->
```typescript
const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.age = 25
await user.save()

const allUsers = await User.find()
const firstUser = await User.findOneBy({
    id: 1,
})
const timber = await User.findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})

await timber.remove()
```

<!-- EN -->
## Installation

<!-- ZH -->
## 安装

<!-- EN -->
1. Install the npm package:

<!-- ZH -->
1. 安装 npm 包：

<!-- EN -->
   `npm install typeorm`

<!-- ZH -->
   `npm install typeorm`

<!-- EN -->
2. You need to install `reflect-metadata` shim:

<!-- ZH -->
2. 你需要安装 `reflect-metadata` 垫片：

<!-- EN -->
   `npm install reflect-metadata`

<!-- ZH -->
   `npm install reflect-metadata`

<!-- EN -->
   and import it somewhere in the global place of your app (for example in `app.ts`):

<!-- ZH -->
   并在应用的全局位置引入它（例如在 `app.ts` 中）：

<!-- EN -->
   `import "reflect-metadata"`

<!-- ZH -->
   `import "reflect-metadata"`

<!-- EN -->
3. You may need to install node typings:

<!-- ZH -->
3. 你可能还需要安装 node 的类型声明：

<!-- EN -->
   `npm install @types/node --save-dev`

<!-- ZH -->
   `npm install @types/node --save-dev`

<!-- EN -->
4. Install a database driver: see the documentation for each particular driver: [mongodb](https://typeorm.io/docs/drivers/mongodb#installation), [mssql](https://typeorm.io/docs/drivers/microsoft-sqlserver#installation), [mysql/mariadb](https://typeorm.io/docs/drivers/mysql#installation), [oracle](https://typeorm.io/docs/drivers/oracle#installation), [postgres](https://typeorm.io/docs/drivers/postgres#installation), [sap](https://typeorm.io/docs/drivers/sap#installation), [spanner](https://typeorm.io/docs/drivers/google-spanner#installation), [sqlite](https://typeorm.io/docs/drivers/sqlite#installation).

<!-- ZH -->
4. 安装数据库驱动：参见各驱动的文档：[mongodb](https://typeorm.io/docs/drivers/mongodb#installation)、[mssql](https://typeorm.io/docs/drivers/microsoft-sqlserver#installation)、[mysql/mariadb](https://typeorm.io/docs/drivers/mysql#installation)、[oracle](https://typeorm.io/docs/drivers/oracle#installation)、[postgres](https://typeorm.io/docs/drivers/postgres#installation)、[sap](https://typeorm.io/docs/drivers/sap#installation)、[spanner](https://typeorm.io/docs/drivers/google-spanner#installation)、[sqlite](https://typeorm.io/docs/drivers/sqlite#installation)。

<!-- EN -->
### TypeScript configuration

<!-- ZH -->
### TypeScript 配置

<!-- EN -->
Also, make sure you are using TypeScript version **4.5** or higher, and you have enabled the following settings in `tsconfig.json`:

<!-- ZH -->
另外，请确保你使用的 TypeScript 版本为 **4.5** 或更高，并在 `tsconfig.json` 中启用以下配置：

<!-- EN -->
```json
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
```

<!-- ZH -->
```json
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
```

<!-- EN -->
## Quick Start

<!-- ZH -->
## 快速上手

<!-- EN -->
The quickest way to get started with TypeORM is to use its CLI commands to generate a starter project. Quick start works only if you are using TypeORM in a Node.js application. If you are using other platforms, proceed to the [step-by-step guide](#step-by-step-guide).

<!-- ZH -->
上手 TypeORM 最快的方式是用它的 CLI 命令生成一个起始项目。快速上手仅在你将 TypeORM 用于 Node.js 应用时可用。如果你使用其他平台，请继续阅读[分步指南](#step-by-step-guide)。

<!-- EN -->
To create a new project using CLI, run the following command:

<!-- ZH -->
使用 CLI 创建新项目，运行以下命令：

<!-- EN -->
```shell
npx typeorm init --name MyProject --database postgres
```

<!-- ZH -->
```shell
npx typeorm init --name MyProject --database postgres
```

<!-- EN -->
Where `name` is the name of your project and `database` is the database you'll use. Database can be one of the following values: `mysql`, `mariadb`, `postgres`, `cockroachdb`, `sqlite`, `mssql`, `sap`, `spanner`, `oracle`, `mongodb`, `cordova`, `react-native`, `expo`, `nativescript`.

<!-- ZH -->
其中 `name` 是项目名称，`database` 是你要使用的数据库。数据库可以是以下值之一：`mysql`、`mariadb`、`postgres`、`cockroachdb`、`sqlite`、`mssql`、`sap`、`spanner`、`oracle`、`mongodb`、`cordova`、`react-native`、`expo`、`nativescript`。

<!-- EN -->
This command will generate a new project in the `MyProject` directory with the following files:

<!-- ZH -->
该命令会在 `MyProject` 目录下生成一个新项目，包含以下文件：

<!-- EN -->
```text
MyProject
├── src                   // place of your TypeScript code
│   ├── entities          // place where your entities (database models) are stored
│   │   └── User.ts       // sample entity
│   ├── migrations        // place where your migrations are stored
│   ├── data-source.ts    // data source and all connection configuration
│   └── index.ts          // start point of your application
├── .gitignore            // standard gitignore file
├── package.json          // node module dependencies
├── README.md             // simple readme file
└── tsconfig.json         // TypeScript compiler options
```

<!-- ZH -->
```text
MyProject
├── src                   // 存放 TypeScript 代码的位置
│   ├── entities          // 存放实体（数据库模型）的位置
│   │   └── User.ts       // 示例实体
│   ├── migrations        // 存放迁移的位置
│   ├── data-source.ts    // 数据源与全部连接配置
│   └── index.ts          // 应用入口
├── .gitignore            // 标准 gitignore 文件
├── package.json          // node 模块依赖
├── README.md             // 简单的 readme 文件
└── tsconfig.json         // TypeScript 编译选项
```

<!-- EN -->
> You can also run `typeorm init` on an existing node project, but be careful - it may override some files you already have.

<!-- ZH -->
> 你也可以在已有的 node 项目上运行 `typeorm init`，但要小心——它可能会覆盖你已有的某些文件。

<!-- EN -->
The next step is to install new project dependencies:

<!-- ZH -->
下一步是安装新项目的依赖：

<!-- EN -->
```shell
cd MyProject
npm install
```

<!-- ZH -->
```shell
cd MyProject
npm install
```

<!-- EN -->
After you have all dependencies installed, edit the `data-source.ts` file and put your own database connection configuration options in there:

<!-- ZH -->
依赖全部安装完成后，编辑 `data-source.ts` 文件，把你自己的数据库连接配置项填进去：

<!-- EN -->
```ts
export const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test",
    synchronize: true,
    logging: true,
    entities: [Post, Category],
    subscribers: [],
    migrations: [],
})
```

<!-- ZH -->
```ts
export const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test",
    synchronize: true,
    logging: true,
    entities: [Post, Category],
    subscribers: [],
    migrations: [],
})
```

<!-- EN -->
Particularly, most of the time you'll only need to configure `host`, `username`, `password`, `database` and maybe `port` options.

<!-- ZH -->
通常情况下，你只需要配置 `host`、`username`、`password`、`database`，也许还有 `port` 这几项。

<!-- EN -->
Once you finish with configuration and all node modules are installed, you can run your application:

<!-- ZH -->
配置完成且所有 node 模块都已安装后，就可以运行你的应用了：

<!-- EN -->
```shell
npm start
```

<!-- ZH -->
```shell
npm start
```

<!-- EN -->
That's it, your application should successfully run and insert a new user into the database. You can continue to work with this project and integrate other modules you need and start creating more entities.

<!-- ZH -->
就这样，你的应用应该能成功运行，并向数据库中插入一条新用户记录。你可以继续在这个项目上工作，集成你需要的其他模块，并开始创建更多实体。

<!-- EN -->
> You can generate an ESM project by running `npx typeorm init --name MyProject --database postgres --module esm` command.

<!-- ZH -->
> 运行 `npx typeorm init --name MyProject --database postgres --module esm` 命令可以生成 ESM 项目。

<!-- EN -->
> You can generate an even more advanced project with express installed by running `npx typeorm init --name MyProject --database mysql --express` command.

<!-- ZH -->
> 运行 `npx typeorm init --name MyProject --database mysql --express` 命令可以生成一个更高级的、已装好 express 的项目。

<!-- EN -->
> You can generate a docker-compose file by running `npx typeorm init --name MyProject --database postgres --docker` command.

<!-- ZH -->
> 运行 `npx typeorm init --name MyProject --database postgres --docker` 命令可以生成 docker-compose 文件。

<!-- EN -->
## Step-by-Step Guide

<!-- ZH -->
## 分步指南

<!-- EN -->
What are you expecting from ORM? First, you are expecting it will create database tables for you and find / insert / update / delete your data without the pain of having to write lots of hardly maintainable SQL queries. This guide will show you how to set up TypeORM from scratch and make it do what you are expecting from an ORM.

<!-- ZH -->
你对 ORM 的期待是什么？首先，你期待它为你创建数据库表，并且不必痛苦地编写大量难以维护的 SQL 查询就能查找 / 插入 / 更新 / 删除数据。本指南将向你展示如何从零搭建 TypeORM，并让它做到你对 ORM 的这些期待。

<!-- EN -->
### Create a model

<!-- ZH -->
### 创建模型

<!-- EN -->
Working with a database starts with creating tables. How do you tell TypeORM to create a database table? The answer is - through the models. Your models in your app are your database tables.

<!-- ZH -->
与数据库打交道从创建表开始。你怎么告诉 TypeORM 去创建一张数据库表？答案是——通过模型。你应用中的模型就是你的数据库表。

<!-- EN -->
For example, you have a `Photo` model:

<!-- ZH -->
例如，你有一个 `Photo` 模型：

<!-- EN -->
```typescript
export class Photo {
    id: number
    name: string
    description: string
    filename: string
    views: number
    isPublished: boolean
}
```

<!-- ZH -->
```typescript
export class Photo {
    id: number
    name: string
    description: string
    filename: string
    views: number
    isPublished: boolean
}
```

<!-- EN -->
And you want to store photos in your database. To store things in the database, first, you need a database table, and database tables are created from your models. Not all models, but only those you define as *entities*.

<!-- ZH -->
你想把照片存进数据库。要把东西存进数据库，首先你需要一张数据库表，而数据库表是由你的模型创建的。不是所有模型都会建表，只有那些被你定义为*实体*的模型才会。

<!-- EN -->
### Create an entity

<!-- ZH -->
### 创建实体

<!-- EN -->
*Entity* is your model decorated by an `@Entity` decorator. A database table will be created for such models. You work with entities everywhere in TypeORM. You can load/insert/update/remove and perform other operations with them.

<!-- ZH -->
*实体*是被 `@Entity` 装饰器修饰的模型。TypeORM 会为这类模型创建数据库表。在 TypeORM 中你到处都在和实体打交道。你可以加载 / 插入 / 更新 / 删除它们，并对其执行其他操作。

<!-- EN -->
Let's make our `Photo` model an entity:

<!-- ZH -->
把我们的 `Photo` 模型变成实体：

<!-- EN -->
```typescript
import { Entity } from "typeorm"

@Entity()
export class Photo {
    id: number
    name: string
    description: string
    filename: string
    views: number
    isPublished: boolean
}
```

<!-- ZH -->
```typescript
import { Entity } from "typeorm"

@Entity()
export class Photo {
    id: number
    name: string
    description: string
    filename: string
    views: number
    isPublished: boolean
}
```

<!-- EN -->
Now, a database table will be created for the `Photo` entity, and we'll be able to work with it anywhere in our app. We have created a database table, however, what table can exist without columns? Let's create a few columns in our database table.

<!-- ZH -->
现在，TypeORM 会为 `Photo` 实体创建一张数据库表，我们就能在应用的任何地方使用它了。我们已经创建了一张数据库表，可是哪张表能没有列呢？接下来给这张表加几列。

<!-- EN -->
### Adding table columns

<!-- ZH -->
### 添加表列

<!-- EN -->
To add database columns, you need to decorate an entity's properties you want to make into a column with a `@Column` decorator.

<!-- ZH -->
要添加数据库列，你需要用 `@Column` 装饰器修饰实体上那些你想变成列的属性。

<!-- EN -->
```typescript
import { Entity, Column } from "typeorm"

@Entity()
export class Photo {
    @Column()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}
```

<!-- ZH -->
```typescript
import { Entity, Column } from "typeorm"

@Entity()
export class Photo {
    @Column()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}
```

<!-- EN -->
Now `id`, `name`, `description`, `filename`, `views`, and `isPublished` columns will be added to the `photo` table. Column types in the database are inferred from the property types you used, e.g. `number` will be converted into `integer`, `string` into `varchar`, `boolean` into `bool`, etc. But you can use any column type your database supports by explicitly specifying a column type into the `@Column` decorator.

<!-- ZH -->
现在 `id`、`name`、`description`、`filename`、`views` 和 `isPublished` 这些列会被添加到 `photo` 表中。数据库中的列类型由你使用的属性类型推断得出，例如 `number` 会被转换成 `integer`，`string` 转换成 `varchar`，`boolean` 转换成 `bool` 等。不过你也可以在 `@Column` 装饰器中显式指定列类型，从而使用数据库支持的任意列类型。

<!-- EN -->
We generated a database table with columns, but there is one thing left. Each database table must have a column with a primary key.

<!-- ZH -->
我们已经生成了一张带列的数据库表，但还剩一件事。每张数据库表都必须有一列作为主键。

<!-- EN -->
### Creating a primary column

<!-- ZH -->
### 创建主键列

<!-- EN -->
Each entity **must** have at least one primary key column. This is a requirement, and you can't avoid it. To make a column a primary key, you need to use the `@PrimaryColumn` decorator.

<!-- ZH -->
每个实体 **必须** 至少有一列主键。这是硬性要求，无法回避。要把某一列变成主键，你需要使用 `@PrimaryColumn` 装饰器。

<!-- EN -->
```typescript
import { Entity, Column, PrimaryColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}
```

<!-- ZH -->
```typescript
import { Entity, Column, PrimaryColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}
```

<!-- EN -->
### Creating an auto-generated column

<!-- ZH -->
### 创建自增列

<!-- EN -->
Now, let's say you want your id column to be auto-generated (this is known as auto-increment / sequence / serial / generated identity column). To do that, you need to change the `@PrimaryColumn` decorator to a `@PrimaryGeneratedColumn` decorator:

<!-- ZH -->
现在，假设你希望 id 列自动生成（也就是所谓的自增 / 序列 / serial / 生成标识列）。要做到这一点，你需要把 `@PrimaryColumn` 装饰器换成 `@PrimaryGeneratedColumn` 装饰器：

<!-- EN -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}
```

<!-- ZH -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}
```

<!-- EN -->
### Column data types

<!-- ZH -->
### 列数据类型

<!-- EN -->
Next, let's fix our data types. By default, the string is mapped to a varchar(255)-like type (depending on the database type). The number is mapped to an integer-like type (depending on the database type). We don't want all our columns to be limited to varchars or integers. Let's set up the correct data types:

<!-- ZH -->
接下来，我们来修正数据类型。默认情况下，string 会被映射为类似 varchar(255) 的类型（取决于数据库类型），number 会被映射为类似 integer 的类型（同样取决于数据库类型）。我们不希望所有列都被限制成 varchar 或 integer。来设置正确的数据类型：

<!-- EN -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column({
        length: 100,
    })
    name: string

    @Column("text")
    description: string

    @Column()
    filename: string

    @Column("double")
    views: number

    @Column()
    isPublished: boolean
}
```

<!-- ZH -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column({
        length: 100,
    })
    name: string

    @Column("text")
    description: string

    @Column()
    filename: string

    @Column("double")
    views: number

    @Column()
    isPublished: boolean
}
```

<!-- EN -->
Column types are database-specific. You can set any column type your database supports. More information on supported column types can be found [here](https://typeorm.io/docs/entity/entities#column-types).

<!-- ZH -->
列类型是数据库专属的。你可以设置数据库支持的任何列类型。关于受支持的列类型的更多信息可以在[这里](https://typeorm.io/docs/entity/entities#column-types)找到。

<!-- EN -->
### Creating a new `DataSource`

<!-- ZH -->
### 创建新的 `DataSource`

<!-- EN -->
Now, when our entity is created, let's create `index.ts` file and set up our `DataSource` there:

<!-- ZH -->
现在实体已经创建好了，我们来创建 `index.ts` 文件，并在其中配置 `DataSource`：

<!-- EN -->
```typescript
import "reflect-metadata"
import { DataSource } from "typeorm"
import { Photo } from "./entity/Photo"

const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "root",
    password: "admin",
    database: "test",
    entities: [Photo],
    synchronize: true,
    logging: false,
})

// to initialize the initial connection with the database, register all entities
// and "synchronize" database schema, call "initialize()" method of a newly created database
// once in your application bootstrap
try {
    await AppDataSource.initialize()
} catch (error) {
    console.log(error)
}
```

<!-- ZH -->
```typescript
import "reflect-metadata"
import { DataSource } from "typeorm"
import { Photo } from "./entity/Photo"

const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "root",
    password: "admin",
    database: "test",
    entities: [Photo],
    synchronize: true,
    logging: false,
})

// 要初始化与数据库的首次连接、注册所有实体并"同步"数据库结构，
// 需要在应用启动时调用一次新建数据库连接实例的 "initialize()" 方法
try {
    await AppDataSource.initialize()
} catch (error) {
    console.log(error)
}
```

<!-- EN -->
We are using Postgres in this example, but you can use any other supported database. To use another database, change the `type` in the options to the database type you are using: `mysql`, `mariadb`, `postgres`, `cockroachdb`, `sqlite`, `mssql`, `oracle`, `sap`, `spanner`, `cordova`, `nativescript`, `react-native`, `expo`, or `mongodb`. Also make sure to use your own host, port, username, password, and database settings.

<!-- ZH -->
本例中使用的是 Postgres，但你可以使用任何其他受支持的数据库。要换用其他数据库，把配置项中的 `type` 改成你正在使用的数据库类型即可：`mysql`、`mariadb`、`postgres`、`cockroachdb`、`sqlite`、`mssql`、`oracle`、`sap`、`spanner`、`cordova`、`nativescript`、`react-native`、`expo` 或 `mongodb`。同时请确保使用你自己的 host、port、username、password 和 database 配置。

<!-- EN -->
We added our Photo entity to the list of entities for this data source. Each entity you are using in your connection must be listed there.

<!-- ZH -->
我们把 Photo 实体加入了该数据源的实体列表。你在连接中用到的每个实体都必须列在那里。

<!-- EN -->
Setting `synchronize` makes sure your entities will be synced with the database, every time you run the application.

<!-- ZH -->
设置 `synchronize` 可以确保每次运行应用时，你的实体都会与数据库保持同步。

<!-- EN -->
### Running the application

<!-- ZH -->
### 运行应用

<!-- EN -->
Now if you run your `index.ts`, a connection with the database will be initialized and a database table for your photos will be created.

<!-- ZH -->
现在如果你运行 `index.ts`，与数据库的连接就会被初始化，并为你创建一张存放照片的数据库表。

<!-- EN -->
```text
+-------------+--------------+----------------------------+
|                         photo                           |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(100) |                            |
| description | text         |                            |
| filename    | varchar(255) |                            |
| views       | int          |                            |
| isPublished | boolean      |                            |
+-------------+--------------+----------------------------+
```

<!-- ZH -->
```text
+-------------+--------------+----------------------------+
|                         photo                           |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(100) |                            |
| description | text         |                            |
| filename    | varchar(255) |                            |
| views       | int          |                            |
| isPublished | boolean      |                            |
+-------------+--------------+----------------------------+
```

<!-- EN -->
### Creating and inserting a photo into the database

<!-- ZH -->
### 创建一张照片并插入数据库

<!-- EN -->
Now let's create a new photo to save it in the database:

<!-- ZH -->
现在我们来创建一张新照片并把它存进数据库：

<!-- EN -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true

await AppDataSource.manager.save(photo)
console.log("Photo has been saved. Photo id is", photo.id)
```

<!-- ZH -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true

await AppDataSource.manager.save(photo)
console.log("Photo has been saved. Photo id is", photo.id)
```

<!-- EN -->
Once your entity is saved, it will get a newly generated id. `save` method returns an instance of the same object you pass to it. It's not a new copy of the object, it modifies its "id" and returns it.

<!-- ZH -->
实体保存后会获得一个新生成的 id。`save` 方法返回的是你传给它的那个对象实例。它不是该对象的新副本，而是修改了它的 "id" 之后把它返回。

<!-- EN -->
### Using Entity Manager

<!-- ZH -->
### 使用 Entity Manager

<!-- EN -->
We just created a new photo and saved it in the database. We used `EntityManager` to save it. Using entity manager, you can manipulate any entity in your app. For example, let's load our saved entity:

<!-- ZH -->
我们刚刚创建了一张新照片并把它存进了数据库，用的是 `EntityManager`。借助 Entity Manager，你可以操作应用中的任何实体。例如，我们来加载刚才保存的实体：

<!-- EN -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const savedPhotos = await AppDataSource.manager.find(Photo)
console.log("All photos from the db: ", savedPhotos)
```

<!-- ZH -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const savedPhotos = await AppDataSource.manager.find(Photo)
console.log("All photos from the db: ", savedPhotos)
```

<!-- EN -->
`savedPhotos` will be an array of Photo objects with the data loaded from the database.

<!-- ZH -->
`savedPhotos` 将是一个 Photo 对象数组，其中的数据来自数据库。

<!-- EN -->
Learn more about [EntityManager](https://typeorm.io/docs/working-with-entity-manager/working-with-entity-manager).

<!-- ZH -->
进一步了解 [EntityManager](https://typeorm.io/docs/working-with-entity-manager/working-with-entity-manager)。

<!-- EN -->
### Using Repositories

<!-- ZH -->
### 使用 Repository

<!-- EN -->
Now let's refactor our code and use `Repository` instead of `EntityManager`. Each entity has its own repository which handles all operations with its entity. When you deal with entities a lot, Repositories are more convenient to use than EntityManagers:

<!-- ZH -->
现在我们重构一下代码，用 `Repository` 代替 `EntityManager`。每个实体都有自己的 repository，负责处理与该实体相关的所有操作。当你经常和实体打交道时，Repository 比 EntityManager 用起来更方便：

<!-- EN -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true

const photoRepository = AppDataSource.getRepository(Photo)

await photoRepository.save(photo)
console.log("Photo has been saved")

const savedPhotos = await photoRepository.find()
console.log("All photos from the db: ", savedPhotos)
```

<!-- ZH -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true

const photoRepository = AppDataSource.getRepository(Photo)

await photoRepository.save(photo)
console.log("Photo has been saved")

const savedPhotos = await photoRepository.find()
console.log("All photos from the db: ", savedPhotos)
```

<!-- EN -->
Learn more about Repository [here](https://typeorm.io/docs/working-with-entity-manager/working-with-repository).

<!-- ZH -->
在[这里](https://typeorm.io/docs/working-with-entity-manager/working-with-repository)进一步了解 Repository。

<!-- EN -->
### Loading from the database

<!-- ZH -->
### 从数据库加载

<!-- EN -->
Let's try more load operations using the Repository:

<!-- ZH -->
我们再用 Repository 试试更多的加载操作：

<!-- EN -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const allPhotos = await photoRepository.find()
console.log("All photos from the db: ", allPhotos)

const firstPhoto = await photoRepository.findOneBy({
    id: 1,
})
console.log("First photo from the db: ", firstPhoto)

const meAndBearsPhoto = await photoRepository.findOneBy({
    name: "Me and Bears",
})
console.log("Me and Bears photo from the db: ", meAndBearsPhoto)

const allViewedPhotos = await photoRepository.findBy({ views: 1 })
console.log("All viewed photos: ", allViewedPhotos)

const allPublishedPhotos = await photoRepository.findBy({ isPublished: true })
console.log("All published photos: ", allPublishedPhotos)

const [photos, photosCount] = await photoRepository.findAndCount()
console.log("All photos: ", photos)
console.log("Photos count: ", photosCount)
```

<!-- ZH -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const allPhotos = await photoRepository.find()
console.log("All photos from the db: ", allPhotos)

const firstPhoto = await photoRepository.findOneBy({
    id: 1,
})
console.log("First photo from the db: ", firstPhoto)

const meAndBearsPhoto = await photoRepository.findOneBy({
    name: "Me and Bears",
})
console.log("Me and Bears photo from the db: ", meAndBearsPhoto)

const allViewedPhotos = await photoRepository.findBy({ views: 1 })
console.log("All viewed photos: ", allViewedPhotos)

const allPublishedPhotos = await photoRepository.findBy({ isPublished: true })
console.log("All published photos: ", allPublishedPhotos)

const [photos, photosCount] = await photoRepository.findAndCount()
console.log("All photos: ", photos)
console.log("Photos count: ", photosCount)
```

<!-- EN -->
### Updating in the database

<!-- ZH -->
### 在数据库中更新

<!-- EN -->
Now let's load a single photo from the database, update it, and save it:

<!-- ZH -->
现在我们从数据库加载一张照片，更新它，再保存回去：

<!-- EN -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const photoToUpdate = await photoRepository.findOneBy({
    id: 1,
})
photoToUpdate.name = "Me, my friends and polar bears"
await photoRepository.save(photoToUpdate)
```

<!-- ZH -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const photoToUpdate = await photoRepository.findOneBy({
    id: 1,
})
photoToUpdate.name = "Me, my friends and polar bears"
await photoRepository.save(photoToUpdate)
```

<!-- EN -->
Now photo with `id = 1` will be updated in the database.

<!-- ZH -->
现在数据库中 `id = 1` 的那张照片就被更新了。

<!-- EN -->
### Removing from the database

<!-- ZH -->
### 从数据库删除

<!-- EN -->
Now let's remove our photo from the database:

<!-- ZH -->
现在我们把照片从数据库中删除：

<!-- EN -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const photoToRemove = await photoRepository.findOneBy({
    id: 1,
})
await photoRepository.remove(photoToRemove)
```

<!-- ZH -->
```typescript
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const photoToRemove = await photoRepository.findOneBy({
    id: 1,
})
await photoRepository.remove(photoToRemove)
```

<!-- EN -->
Now photo with `id = 1` will be removed from the database.

<!-- ZH -->
现在数据库中 `id = 1` 的那张照片就被删除了。

<!-- EN -->
### Creating a one-to-one relation

<!-- ZH -->
### 创建一对一关系

<!-- EN -->
Let's create a one-to-one relationship with another class. Let's create a new class in `PhotoMetadata.ts`. This PhotoMetadata class is supposed to contain our photo's additional meta-information:

<!-- ZH -->
我们来和另一个类创建一对一关系。在 `PhotoMetadata.ts` 中新建一个类。这个 PhotoMetadata 类用来存放照片的额外元信息：

<!-- EN -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class PhotoMetadata {
    @PrimaryGeneratedColumn()
    id: number

    @Column("int")
    height: number

    @Column("int")
    width: number

    @Column()
    orientation: string

    @Column()
    compressed: boolean

    @Column()
    comment: string

    @OneToOne(() => Photo)
    @JoinColumn()
    photo: Photo
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class PhotoMetadata {
    @PrimaryGeneratedColumn()
    id: number

    @Column("int")
    height: number

    @Column("int")
    width: number

    @Column()
    orientation: string

    @Column()
    compressed: boolean

    @Column()
    comment: string

    @OneToOne(() => Photo)
    @JoinColumn()
    photo: Photo
}
```

<!-- EN -->
Here, we are using a new decorator called `@OneToOne`. It allows us to create a one-to-one relationship between two entities. We also add a `@JoinColumn` decorator, which indicates that this side of the relationship will own the relationship. Relations can be unidirectional or bidirectional. Only one side of the relation can be the owner. Using `@JoinColumn` decorator is required on the owner side of the relationship.

<!-- ZH -->
这里我们用了一个新的装饰器 `@OneToOne`。它让我们能在两个实体之间建立一对一关系。我们还加上了 `@JoinColumn` 装饰器，它表示关系的这一方将拥有该关系。关系可以是单向的，也可以是双向的。关系只有一方能成为拥有方。在关系的拥有方上必须使用 `@JoinColumn` 装饰器。

<!-- EN -->
If you run the app, you'll see a newly generated table, and it will contain a column with a foreign key for the photo relation:

<!-- ZH -->
运行应用后，你会看到一张新生成的表，其中包含一个指向 photo 关系的外键列：

<!-- EN -->
```text
+-------------+--------------+----------------------------+
|                     photo_metadata                      |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| height      | int          |                            |
| width       | int          |                            |
| comment     | varchar(255) |                            |
| compressed  | boolean      |                            |
| orientation | varchar(255) |                            |
| photoId     | int          | FOREIGN KEY                |
+-------------+--------------+----------------------------+
```

<!-- ZH -->
```text
+-------------+--------------+----------------------------+
|                     photo_metadata                      |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| height      | int          |                            |
| width       | int          |                            |
| comment     | varchar(255) |                            |
| compressed  | boolean      |                            |
| orientation | varchar(255) |                            |
| photoId     | int          | FOREIGN KEY                |
+-------------+--------------+----------------------------+
```

<!-- EN -->
### Save a one-to-one relation

<!-- ZH -->
### 保存一对一关系

<!-- EN -->
Now let's save a photo and its metadata and attach them to each other.

<!-- ZH -->
现在我们保存一张照片及其元数据，并把它们关联起来。

<!-- EN -->
```typescript
import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"

// Create a photo
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true

// Create a photo metadata
const metadata = new PhotoMetadata()
metadata.height = 640
metadata.width = 480
metadata.compressed = true
metadata.comment = "cybershoot"
metadata.orientation = "portrait"
metadata.photo = photo // this way we connect them

// Get entity repositories
const photoRepository = AppDataSource.getRepository(Photo)
const metadataRepository = AppDataSource.getRepository(PhotoMetadata)

// First we should save a photo
await photoRepository.save(photo)

// The Photo is saved. Now we need to save a photo metadata
await metadataRepository.save(metadata)

// Done
console.log(
    "Metadata is saved, and the relation between metadata and photo is created in the database too",
)
```

<!-- ZH -->
```typescript
import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"

// 创建一张照片
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true

// 创建照片元数据
const metadata = new PhotoMetadata()
metadata.height = 640
metadata.width = 480
metadata.compressed = true
metadata.comment = "cybershoot"
metadata.orientation = "portrait"
metadata.photo = photo // 这样就把它们关联起来了

// 获取实体 repository
const photoRepository = AppDataSource.getRepository(Photo)
const metadataRepository = AppDataSource.getRepository(PhotoMetadata)

// 先保存照片
await photoRepository.save(photo)

// 照片已保存。现在保存照片元数据
await metadataRepository.save(metadata)

// 完成
console.log(
    "Metadata is saved, and the relation between metadata and photo is created in the database too",
)
```

<!-- EN -->
### Inverse side of the relationship

<!-- ZH -->
### 关系的反向方

<!-- EN -->
Relations can be unidirectional or bidirectional. Currently, our relation between PhotoMetadata and Photo is unidirectional. The owner of the relation is PhotoMetadata, and Photo doesn't know anything about PhotoMetadata. This makes it complicated to access PhotoMetadata from the Photo side. To fix this issue, we should add an inverse relation, and make relations between PhotoMetadata and Photo bidirectional. Let's modify our entities:

<!-- ZH -->
关系可以是单向的，也可以是双向的。目前 PhotoMetadata 与 Photo 之间的关系是单向的。关系的拥有方是 PhotoMetadata，而 Photo 对 PhotoMetadata 一无所知。这使得从 Photo 一侧访问 PhotoMetadata 变得很麻烦。要解决这个问题，我们应该加一个反向关系，让 PhotoMetadata 与 Photo 之间的关系变成双向的。我们来修改实体：

<!-- EN -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class PhotoMetadata {
    /* ... other columns */

    @OneToOne(() => Photo, (photo) => photo.metadata)
    @JoinColumn()
    photo: Photo
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class PhotoMetadata {
    /* ... 其他列 */

    @OneToOne(() => Photo, (photo) => photo.metadata)
    @JoinColumn()
    photo: Photo
}
```

<!-- EN -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"

@Entity()
export class Photo {
    /* ... other columns */

    @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
    metadata: PhotoMetadata
}
```

<!-- ZH -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"

@Entity()
export class Photo {
    /* ... 其他列 */

    @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
    metadata: PhotoMetadata
}
```

<!-- EN -->
`photo => photo.metadata` is a function that returns the name of the inverse side of the relation. Here we show that the metadata property of the Photo class is where we store PhotoMetadata in the Photo class. Instead of passing a function that returns a property of the photo, you could alternatively pass a string to `@OneToOne` decorator, like `"metadata"`. But we used this function-typed approach to make our refactoring easier.

<!-- ZH -->
`photo => photo.metadata` 是一个返回关系反向方名称的函数。这里我们表明，Photo 类的 metadata 属性就是我们在 Photo 类中存放 PhotoMetadata 的地方。除了传入一个返回 photo 属性的函数，你也可以给 `@OneToOne` 装饰器传一个字符串，比如 `"metadata"`。不过我们采用这种函数式写法，是为了让重构更容易。

<!-- EN -->
Note that we should use the `@JoinColumn` decorator only on one side of a relation. Whichever side you put this decorator on will be the owning side of the relationship. The owning side of a relationship contains a column with a foreign key in the database.

<!-- ZH -->
注意，`@JoinColumn` 装饰器只能在关系的一侧使用。你把该装饰器放在哪一侧，哪一侧就是关系的拥有方。关系的拥有方在数据库中持有带外键的那一列。

<!-- EN -->
### Relations in ESM projects

<!-- ZH -->
### ESM 项目中的关系

<!-- EN -->
If you use ESM in your TypeScript project, you should use the `Relation` wrapper type in relation properties to avoid circular dependency issues. Let's modify our entities:

<!-- ZH -->
如果你的 TypeScript 项目使用 ESM，那么在关系属性上应使用 `Relation` 包装类型，以避免循环依赖问题。我们来修改实体：

<!-- EN -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    JoinColumn,
    Relation,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class PhotoMetadata {
    /* ... other columns */

    @OneToOne(() => Photo, (photo) => photo.metadata)
    @JoinColumn()
    photo: Relation<Photo>
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    JoinColumn,
    Relation,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class PhotoMetadata {
    /* ... 其他列 */

    @OneToOne(() => Photo, (photo) => photo.metadata)
    @JoinColumn()
    photo: Relation<Photo>
}
```

<!-- EN -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    Relation,
} from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"

@Entity()
export class Photo {
    /* ... other columns */

    @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
    metadata: Relation<PhotoMetadata>
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    Relation,
} from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"

@Entity()
export class Photo {
    /* ... 其他列 */

    @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
    metadata: Relation<PhotoMetadata>
}
```

<!-- EN -->
### Loading objects with their relations

<!-- ZH -->
### 加载对象及其关系

<!-- EN -->
Now let's load our photo and its photo metadata in a single query. There are two ways to do it - using `find*` methods or using `QueryBuilder` functionality. Let's use `find*` method first. `find*` methods allow you to specify an object with the `FindOneOptions` / `FindManyOptions` interface.

<!-- ZH -->
现在我们用一条查询加载照片及其照片元数据。有两种方式可以做到——使用 `find*` 方法，或者使用 `QueryBuilder` 功能。我们先用 `find*` 方法。`find*` 方法允许你传入一个符合 `FindOneOptions` / `FindManyOptions` 接口的对象。

<!-- EN -->
```typescript
import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const photos = await photoRepository.find({
    relations: {
        metadata: true,
    },
})
```

<!-- ZH -->
```typescript
import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const photos = await photoRepository.find({
    relations: {
        metadata: true,
    },
})
```

<!-- EN -->
Here, photos will contain an array of photos from the database, and each photo will contain its photo metadata. Learn more about Find Options in [this documentation](https://typeorm.io/docs/working-with-entity-manager/find-options).

<!-- ZH -->
这里，photos 会包含一个来自数据库的照片数组，并且每张照片都带有它的照片元数据。在[这份文档](https://typeorm.io/docs/working-with-entity-manager/find-options)中进一步了解 Find Options。

<!-- EN -->
Using find options is good and dead simple, but if you need a more complex query, you should use `QueryBuilder` instead. `QueryBuilder` allows more complex queries to be used elegantly:

<!-- ZH -->
使用查找选项很好而且极其简单，但如果你需要更复杂的查询，就该改用 `QueryBuilder`。`QueryBuilder` 能让你优雅地写出更复杂的查询：

<!-- EN -->
```typescript
import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"
import { AppDataSource } from "./index"

const photos = await AppDataSource.getRepository(Photo)
    .createQueryBuilder("photo")
    .innerJoinAndSelect("photo.metadata", "metadata")
    .getMany()
```

<!-- ZH -->
```typescript
import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"
import { AppDataSource } from "./index"

const photos = await AppDataSource.getRepository(Photo)
    .createQueryBuilder("photo")
    .innerJoinAndSelect("photo.metadata", "metadata")
    .getMany()
```

<!-- EN -->
`QueryBuilder` allows the creation and execution of SQL queries of almost any complexity. When you work with `QueryBuilder`, think like you are creating an SQL query. In this example, "photo" and "metadata" are aliases applied to selected photos. You use aliases to access columns and properties of the selected data.

<!-- ZH -->
`QueryBuilder` 几乎可以创建并执行任意复杂度的 SQL 查询。使用 `QueryBuilder` 时，请把自己想象成正在编写一条 SQL 查询。在这个例子中，"photo" 和 "metadata" 是应用在被选中照片上的别名。你通过别名来访问被选中数据的列和属性。

<!-- EN -->
### Using cascades to automatically save related objects

<!-- ZH -->
### 使用级联自动保存关联对象

<!-- EN -->
We can set up cascade options in our relations, in the cases when we want our related object to be saved whenever the other object is saved. Let's change our photo's `@OneToOne` decorator a bit:

<!-- ZH -->
当我们希望在保存某个对象时自动保存其关联对象，就可以在关系上配置级联选项。我们稍微改一下 Photo 的 `@OneToOne` 装饰器：

<!-- EN -->
```typescript
export class Photo {
    // ... other columns

    @OneToOne(() => PhotoMetadata, (metadata) => metadata.photo, {
        cascade: true,
    })
    metadata: PhotoMetadata
}
```

<!-- ZH -->
```typescript
export class Photo {
    // ... 其他列

    @OneToOne(() => PhotoMetadata, (metadata) => metadata.photo, {
        cascade: true,
    })
    metadata: PhotoMetadata
}
```

<!-- EN -->
Using `cascade` allows us not to separately save photos and separately save metadata objects now. Now we can simply save a photo object, and the metadata object will be saved automatically because of cascade options.

<!-- ZH -->
使用 `cascade` 之后，我们就不必再分别保存照片和元数据对象了。现在我们只需保存照片对象，得益于级联选项，元数据对象会被自动保存。

<!-- EN -->
```typescript
import { AppDataSource } from "./index"

// create photo object
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.isPublished = true

// create photo metadata object
const metadata = new PhotoMetadata()
metadata.height = 640
metadata.width = 480
metadata.compressed = true
metadata.comment = "cybershoot"
metadata.orientation = "portrait"

photo.metadata = metadata // this way we connect them

// get repository
const photoRepository = AppDataSource.getRepository(Photo)

// saving a photo also save the metadata
await photoRepository.save(photo)

console.log("Photo is saved, photo metadata is saved too.")
```

<!-- ZH -->
```typescript
import { AppDataSource } from "./index"

// 创建照片对象
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.isPublished = true

// 创建照片元数据对象
const metadata = new PhotoMetadata()
metadata.height = 640
metadata.width = 480
metadata.compressed = true
metadata.comment = "cybershoot"
metadata.orientation = "portrait"

photo.metadata = metadata // 这样就把它们关联起来了

// 获取 repository
const photoRepository = AppDataSource.getRepository(Photo)

// 保存照片的同时也会保存元数据
await photoRepository.save(photo)

console.log("Photo is saved, photo metadata is saved too.")
```

<!-- EN -->
Notice that we now set the photo's `metadata` property, instead of the metadata's `photo` property as before. The `cascade` feature only works if you connect the photo to its metadata from the photo's side. If you set the metadata side, the metadata would not be saved automatically.

<!-- ZH -->
注意，现在我们设置的是照片的 `metadata` 属性，而不是像之前那样设置元数据的 `photo` 属性。只有当你从照片一侧把照片和它的元数据关联起来时，`cascade` 特性才会生效。如果你设置的是元数据一侧，元数据不会被自动保存。

<!-- EN -->
### Creating a many-to-one / one-to-many relation

<!-- ZH -->
### 创建多对一 / 一对多关系

<!-- EN -->
Let's create a many-to-one/one-to-many relation. Let's say a photo has one author, and each author can have many photos. First, let's create an `Author` class:

<!-- ZH -->
我们来创建一个多对一 / 一对多关系。假设一张照片有一位作者，而每位作者可以有多张照片。首先，创建一个 `Author` 类：

<!-- EN -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToMany,
    JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class Author {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @OneToMany(() => Photo, (photo) => photo.author) // note: we will create author property in the Photo class below
    photos: Photo[]
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToMany,
    JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class Author {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @OneToMany(() => Photo, (photo) => photo.author) // 注意：我们稍后会在 Photo 类中创建 author 属性
    photos: Photo[]
}
```

<!-- EN -->
`Author` contains an inverse side of a relation. `OneToMany` is always an inverse side of the relation, and it can't exist without `ManyToOne` on the other side of the relation.

<!-- ZH -->
`Author` 持有关系的反向方。`OneToMany` 永远是关系的反向方，它不能脱离关系另一侧的 `ManyToOne` 单独存在。

<!-- EN -->
Now let's add the owner side of the relation into the Photo entity:

<!-- ZH -->
现在把关系的拥有方加进 Photo 实体：

<!-- EN -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"
import { Author } from "./Author"

@Entity()
export class Photo {
    /* ... other columns */

    @ManyToOne(() => Author, (author) => author.photos)
    author: Author
}
```

<!-- ZH -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"
import { Author } from "./Author"

@Entity()
export class Photo {
    /* ... 其他列 */

    @ManyToOne(() => Author, (author) => author.photos)
    author: Author
}
```

<!-- EN -->
In many-to-one / one-to-many relations, the owner side is always many-to-one. It means that the class that uses `@ManyToOne` will store the id of the related object.

<!-- ZH -->
在多对一 / 一对多关系中，拥有方永远是多对一方。也就是说，使用 `@ManyToOne` 的那个类会存放关联对象的 id。

<!-- EN -->
After you run the application, the ORM will create the `author` table:

<!-- ZH -->
运行应用后，ORM 会创建 `author` 表：

<!-- EN -->
```text
+-------------+--------------+----------------------------+
|                          author                         |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
+-------------+--------------+----------------------------+
```

<!-- ZH -->
```text
+-------------+--------------+----------------------------+
|                          author                         |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
+-------------+--------------+----------------------------+
```

<!-- EN -->
It will also modify the `photo` table, adding a new `author` column and creating a foreign key for it:

<!-- ZH -->
它还会修改 `photo` 表，新增一个 `author` 列并为其创建外键：

<!-- EN -->
```text
+-------------+--------------+----------------------------+
|                         photo                           |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
| description | varchar(255) |                            |
| filename    | varchar(255) |                            |
| isPublished | boolean      |                            |
| authorId    | int          | FOREIGN KEY                |
+-------------+--------------+----------------------------+
```

<!-- ZH -->
```text
+-------------+--------------+----------------------------+
|                         photo                           |
+-------------+--------------+----------------------------+
| id          | int          | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
| description | varchar(255) |                            |
| filename    | varchar(255) |                            |
| isPublished | boolean      |                            |
| authorId    | int          | FOREIGN KEY                |
+-------------+--------------+----------------------------+
```

<!-- EN -->
### Creating a many-to-many relation

<!-- ZH -->
### 创建多对多关系

<!-- EN -->
Let's create a many-to-many relation. Let's say a photo can be in many albums, and each album can contain many photos. Let's create an `Album` class:

<!-- ZH -->
我们来创建一个多对多关系。假设一张照片可以出现在多个相册中，而每个相册可以包含多张照片。创建一个 `Album` 类：

<!-- EN -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToMany,
    JoinTable,
} from "typeorm"

@Entity()
export class Album {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @ManyToMany(() => Photo, (photo) => photo.albums)
    @JoinTable()
    photos: Photo[]
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToMany,
    JoinTable,
} from "typeorm"

@Entity()
export class Album {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @ManyToMany(() => Photo, (photo) => photo.albums)
    @JoinTable()
    photos: Photo[]
}
```

<!-- EN -->
`@JoinTable` is required to specify that this is the owner side of the relationship.

<!-- ZH -->
必须使用 `@JoinTable` 来指明这一侧是关系的拥有方。

<!-- EN -->
Now let's add the inverse side of our relation to the `Photo` class:

<!-- ZH -->
现在把关系的反向方加到 `Photo` 类中：

<!-- EN -->
```typescript
export class Photo {
    // ... other columns

    @ManyToMany(() => Album, (album) => album.photos)
    albums: Album[]
}
```

<!-- ZH -->
```typescript
export class Photo {
    // ... 其他列

    @ManyToMany(() => Album, (album) => album.photos)
    albums: Album[]
}
```

<!-- EN -->
After you run the application, the ORM will create an **album_photos_photo_albums** *junction table*:

<!-- ZH -->
运行应用后，ORM 会创建一张 **album_photos_photo_albums** *中间表*：

<!-- EN -->
```text
+-------------+--------------+----------------------------+
|                album_photos_photo_albums                |
+-------------+--------------+----------------------------+
| album_id    | int          | PRIMARY KEY FOREIGN KEY    |
| photo_id    | int          | PRIMARY KEY FOREIGN KEY    |
+-------------+--------------+----------------------------+
```

<!-- ZH -->
```text
+-------------+--------------+----------------------------+
|                album_photos_photo_albums                |
+-------------+--------------+----------------------------+
| album_id    | int          | PRIMARY KEY FOREIGN KEY    |
| photo_id    | int          | PRIMARY KEY FOREIGN KEY    |
+-------------+--------------+----------------------------+
```

<!-- EN -->
Remember to register the `Album` class with your connection in the ORM:

<!-- ZH -->
别忘了在 ORM 中把 `Album` 类注册到你的连接里：

<!-- EN -->
```typescript
const options: DataSourceOptions = {
    // ... other options
    entities: [Photo, PhotoMetadata, Author, Album],
}
```

<!-- ZH -->
```typescript
const options: DataSourceOptions = {
    // ... 其他选项
    entities: [Photo, PhotoMetadata, Author, Album],
}
```

<!-- EN -->
Now let's insert albums and photos into our database:

<!-- ZH -->
现在我们把相册和照片插入数据库：

<!-- EN -->
```typescript
import { AppDataSource } from "./index"

// create a few albums
const album1 = new Album()
album1.name = "Bears"
await AppDataSource.manager.save(album1)

const album2 = new Album()
album2.name = "Me"
await AppDataSource.manager.save(album2)

// create a few photos
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true
photo.albums = [album1, album2]
await AppDataSource.manager.save(photo)

// now our photo is saved and albums are attached to it
// now lets load them:
const loadedPhoto = await AppDataSource.getRepository(Photo).findOne({
    where: {
        id: 1,
    },
    relations: {
        albums: true,
    },
})
```

<!-- ZH -->
```typescript
import { AppDataSource } from "./index"

// 创建几个相册
const album1 = new Album()
album1.name = "Bears"
await AppDataSource.manager.save(album1)

const album2 = new Album()
album2.name = "Me"
await AppDataSource.manager.save(album2)

// 创建几张照片
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true
photo.albums = [album1, album2]
await AppDataSource.manager.save(photo)

// 现在照片已保存，相册也已关联到它
// 现在把它们加载出来：
const loadedPhoto = await AppDataSource.getRepository(Photo).findOne({
    where: {
        id: 1,
    },
    relations: {
        albums: true,
    },
})
```

<!-- EN -->
`loadedPhoto` will be equal to:

<!-- ZH -->
`loadedPhoto` 将等于：

<!-- EN -->
```typescript
{
    id: 1,
    name: "Me and Bears",
    description: "I am near polar bears",
    filename: "photo-with-bears.jpg",
    albums: [{
        id: 1,
        name: "Bears"
    }, {
        id: 2,
        name: "Me"
    }]
}
```

<!-- ZH -->
```typescript
{
    id: 1,
    name: "Me and Bears",
    description: "I am near polar bears",
    filename: "photo-with-bears.jpg",
    albums: [{
        id: 1,
        name: "Bears"
    }, {
        id: 2,
        name: "Me"
    }]
}
```

<!-- EN -->
### Using QueryBuilder

<!-- ZH -->
### 使用 QueryBuilder

<!-- EN -->
You can use QueryBuilder to build SQL queries of almost any complexity. For example, you can do this:

<!-- ZH -->
你可以用 QueryBuilder 构建几乎任意复杂度的 SQL 查询。例如，你可以这样做：

<!-- EN -->
```typescript
const photos = await AppDataSource.getRepository(Photo)
    .createQueryBuilder("photo") // First argument is an alias. Alias is what you are selecting - photos. You must specify it.
    .innerJoinAndSelect("photo.metadata", "metadata")
    .leftJoinAndSelect("photo.albums", "album")
    .where("photo.isPublished = true")
    .andWhere("(photo.name = :photoName OR photo.name = :bearName)")
    .orderBy("photo.id", "DESC")
    .skip(5)
    .take(10)
    .setParameters({ photoName: "My", bearName: "Mishka" })
    .getMany()
```

<!-- ZH -->
```typescript
const photos = await AppDataSource.getRepository(Photo)
    .createQueryBuilder("photo") // 第一个参数是别名。别名就是你正在选取的东西——照片。你必须指定它。
    .innerJoinAndSelect("photo.metadata", "metadata")
    .leftJoinAndSelect("photo.albums", "album")
    .where("photo.isPublished = true")
    .andWhere("(photo.name = :photoName OR photo.name = :bearName)")
    .orderBy("photo.id", "DESC")
    .skip(5)
    .take(10)
    .setParameters({ photoName: "My", bearName: "Mishka" })
    .getMany()
```

<!-- EN -->
This query selects all published photos with "My" or "Mishka" names. It will select results from position 5 (pagination offset) and will select only 10 results (pagination limit). The selection result will be ordered by id in descending order. The photo albums will be left joined and their metadata will be inner-joined.

<!-- ZH -->
这条查询会选出所有已发布、且名称为 "My" 或 "Mishka" 的照片。它会从第 5 条位置开始选取（分页偏移量），并且只选取 10 条结果（分页限制）。选取结果按 id 降序排列。照片的相册会被左连接，其元数据会被内连接。

<!-- EN -->
You'll use the query builder in your application a lot. Learn more about QueryBuilder [here](https://typeorm.io/docs/query-builder/select-query-builder).

<!-- ZH -->
你会在应用中大量使用 query builder。在[这里](https://typeorm.io/docs/query-builder/select-query-builder)进一步了解 QueryBuilder。

<!-- EN -->
## Extensions

<!-- ZH -->
## 扩展

<!-- EN -->
There are several extensions that simplify working with TypeORM and integrating it with other modules:

<!-- ZH -->
有若干扩展可以简化 TypeORM 的使用，并把它与其他模块集成：

<!-- EN -->
* Models generation from the existing database - [typeorm-model-generator](https://github.com/Kononnable/typeorm-model-generator)
* Fixtures loader - [typeorm-fixtures-cli](https://github.com/RobinCK/typeorm-fixtures)
* ER Diagram generator - [typeorm-uml](https://github.com/eugene-manuilov/typeorm-uml/)
* another ER Diagram generator - [erdia](https://www.npmjs.com/package/erdia/)
* Create, drop and seed database - [typeorm-extension](https://github.com/tada5hi/typeorm-extension)
* Automatically update `data-source.ts` after generating [migrations](https://typeorm.io/docs/migrations/why)/entities - [typeorm-codebase-sync](https://www.npmjs.com/package/typeorm-codebase-sync)
* Easy manipulation of `relations` objects - [typeorm-relations](https://npmjs.com/package/typeorm-relations)
* Automatically generate `relations` based on a GraphQL query - [typeorm-relations-graphql](https://npmjs.com/package/typeorm-relations-graphql)

<!-- ZH -->
* 从已有数据库生成模型 - [typeorm-model-generator](https://github.com/Kononnable/typeorm-model-generator)
* 夹具（fixtures）加载器 - [typeorm-fixtures-cli](https://github.com/RobinCK/typeorm-fixtures)
* ER 图生成器 - [typeorm-uml](https://github.com/eugene-manuilov/typeorm-uml/)
* 另一个 ER 图生成器 - [erdia](https://www.npmjs.com/package/erdia/)
* 创建、删除并填充数据库种子数据 - [typeorm-extension](https://github.com/tada5hi/typeorm-extension)
* 生成[迁移](https://typeorm.io/docs/migrations/why)/实体后自动更新 `data-source.ts` - [typeorm-codebase-sync](https://www.npmjs.com/package/typeorm-codebase-sync)
* 便捷操作 `relations` 对象 - [typeorm-relations](https://npmjs.com/package/typeorm-relations)
* 基于 GraphQL 查询自动生成 `relations` - [typeorm-relations-graphql](https://npmjs.com/package/typeorm-relations-graphql)

<!-- EN -->
## Contributing

<!-- ZH -->
## 贡献

<!-- EN -->
Learn about contribution [here](https://github.com/typeorm/typeorm/blob/master/CONTRIBUTING.md) and how to set up your development environment [here](https://github.com/typeorm/typeorm/blob/master/DEVELOPER.md).

<!-- ZH -->
在[这里](https://github.com/typeorm/typeorm/blob/master/CONTRIBUTING.md)了解如何贡献，在[这里](https://github.com/typeorm/typeorm/blob/master/DEVELOPER.md)了解如何搭建开发环境。

<!-- EN -->
This project exists thanks to all the people who contribute:

<!-- ZH -->
本项目得以存在，要感谢所有做出贡献的人：

<!-- EN -->
[![](https://opencollective.com/typeorm/contributors.svg?width=890\&showBtn=false)](https://github.com/typeorm/typeorm/graphs/contributors)

<!-- ZH -->
[![](https://opencollective.com/typeorm/contributors.svg?width=890\&showBtn=false)](https://github.com/typeorm/typeorm/graphs/contributors)

<!-- EN -->
## Sponsors

<!-- ZH -->
## 赞助者

<!-- EN -->
Open source is hard and time-consuming. If you want to invest in TypeORM's future, you can become a sponsor and allow our core team to spend more time on TypeORM's improvements and new features. [Become a sponsor](https://opencollective.com/typeorm)

<!-- ZH -->
开源既困难又耗时。如果你愿意为 TypeORM 的未来投资，可以成为赞助者，让我们的核心团队把更多时间花在 TypeORM 的改进与新特性上。[成为赞助者](https://opencollective.com/typeorm)

<!-- EN -->
[![](https://opencollective.com/typeorm/tiers/sponsor.svg?width=890)](https://opencollective.com/typeorm)

<!-- ZH -->
[![](https://opencollective.com/typeorm/tiers/sponsor.svg?width=890)](https://opencollective.com/typeorm)

<!-- EN -->
## Gold Sponsors

<!-- ZH -->
## 金牌赞助者

<!-- EN -->
Become a gold sponsor and get premium technical support from our core contributors. [Become a gold sponsor](https://opencollective.com/typeorm)

<!-- ZH -->
成为金牌赞助者，可获得我们核心贡献者提供的优质技术支持。[成为金牌赞助者](https://opencollective.com/typeorm)

<!-- EN -->
[![](https://opencollective.com/typeorm/tiers/gold-sponsor.svg?width=890)](https://opencollective.com/typeorm)

<!-- ZH -->
[![](https://opencollective.com/typeorm/tiers/gold-sponsor.svg?width=890)](https://opencollective.com/typeorm)
