# 从 Sequelize 迁移到 TypeORM

> 英文标题：Migration from Sequelize to TypeORM
> 官网原文：https://typeorm.io/docs/guides/sequelize-migration
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 68 块

---

<!-- EN -->
# Migration from Sequelize to TypeORM

<!-- ZH -->
# 从 Sequelize 迁移到 TypeORM

<!-- EN -->
## Setting up a data source

<!-- ZH -->
## 配置数据源

<!-- EN -->
In sequelize you create a data source this way:

<!-- ZH -->
在 sequelize 中你这样创建数据源：

<!-- EN -->
```javascript
const sequelize = new Sequelize("database", "username", "password", {
    host: "localhost",
    dialect: "mysql",
})

sequelize
    .authenticate()
    .then(() => {
        console.log("Data Source has been initialized successfully.")
    })
    .catch((err) => {
        console.error("Error during Data Source initialization:", err)
    })
```

<!-- ZH -->
```javascript
const sequelize = new Sequelize("database", "username", "password", {
    host: "localhost",
    dialect: "mysql",
})

sequelize
    .authenticate()
    .then(() => {
        console.log("Data Source has been initialized successfully.")
    })
    .catch((err) => {
        console.error("Error during Data Source initialization:", err)
    })
```

<!-- EN -->
In TypeORM you create a data source following way:

<!-- ZH -->
在 TypeORM 中你按下面的方式创建数据源：

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

const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    username: "username",
    password: "password",
})

dataSource
    .initialize()
    .then(() => {
        console.log("Data Source has been initialized successfully.")
    })
    .catch((err) => {
        console.error("Error during Data Source initialization:", err)
    })
```

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

const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    username: "username",
    password: "password",
})

dataSource
    .initialize()
    .then(() => {
        console.log("Data Source has been initialized successfully.")
    })
    .catch((err) => {
        console.error("Error during Data Source initialization:", err)
    })
```

<!-- EN -->
Then you can use `dataSource` instance from anywhere in your app.

<!-- ZH -->
之后你就可以在应用的任何地方使用 `dataSource` 实例了。

<!-- EN -->
Learn more about [Data Source](https://typeorm.io/docs/data-source/data-source)

<!-- ZH -->
进一步了解[数据源](https://typeorm.io/docs/data-source/data-source)

<!-- EN -->
## Schema synchronization

<!-- ZH -->
## 结构同步

<!-- EN -->
In sequelize you do schema synchronization this way:

<!-- ZH -->
在 sequelize 中你这样进行结构同步：

<!-- EN -->
```javascript
Project.sync({ force: true })
Task.sync({ force: true })
```

<!-- ZH -->
```javascript
Project.sync({ force: true })
Task.sync({ force: true })
```

<!-- EN -->
In TypeORM you just add `synchronize: true` in the data source options:

<!-- ZH -->
在 TypeORM 中你只需在数据源选项里加上 `synchronize: true`：

<!-- EN -->
```typescript
const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    username: "username",
    password: "password",
    synchronize: true,
})
```

<!-- ZH -->
```typescript
const dataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    username: "username",
    password: "password",
    synchronize: true,
})
```

<!-- EN -->
## Creating a models

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

<!-- EN -->
This is how models are defined in sequelize:

<!-- ZH -->
这是 sequelize 中定义模型的方式：

<!-- EN -->
```javascript
module.exports = function (sequelize, DataTypes) {
    const Project = sequelize.define("project", {
        title: DataTypes.STRING,
        description: DataTypes.TEXT,
    })

    return Project
}
```

<!-- ZH -->
```javascript
module.exports = function (sequelize, DataTypes) {
    const Project = sequelize.define("project", {
        title: DataTypes.STRING,
        description: DataTypes.TEXT,
    })

    return Project
}
```

<!-- EN -->
```javascript
module.exports = function (sequelize, DataTypes) {
    const Task = sequelize.define("task", {
        title: DataTypes.STRING,
        description: DataTypes.TEXT,
        deadline: DataTypes.DATE,
    })

    return Task
}
```

<!-- ZH -->
```javascript
module.exports = function (sequelize, DataTypes) {
    const Task = sequelize.define("task", {
        title: DataTypes.STRING,
        description: DataTypes.TEXT,
        deadline: DataTypes.DATE,
    })

    return Task
}
```

<!-- EN -->
In TypeORM these models are called entities and you can define them the following way:

<!-- ZH -->
在 TypeORM 中这些模型被称为实体，你可以按下面的方式定义它们：

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

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

    @Column()
    title: string

    @Column()
    description: string
}
```

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

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

    @Column()
    title: string

    @Column()
    description: string
}
```

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

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

    @Column()
    title: string

    @Column("text")
    description: string

    @Column()
    deadline: Date
}
```

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

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

    @Column()
    title: string

    @Column("text")
    description: string

    @Column()
    deadline: Date
}
```

<!-- EN -->
It's highly recommended defining one entity class per file. TypeORM allows you to use your classes as database models and provides a declarative way to define what part of your model will become part of your database table. The power of TypeScript gives you type hinting and other useful features that you can use in classes.

<!-- ZH -->
强烈建议每个文件只定义一个实体类。TypeORM 允许你把自己的类用作数据库模型，并提供了一种声明式方式来定义模型的哪一部分会成为数据库表的一部分。TypeScript 的能力为你提供了类型提示以及其他可在类中使用的实用特性。

<!-- EN -->
Learn more about [Entities and columns](https://typeorm.io/docs/entity/entities)

<!-- ZH -->
进一步了解[实体与列](https://typeorm.io/docs/entity/entities)

<!-- EN -->
## Other model settings

<!-- ZH -->
## 其他模型设置

<!-- EN -->
The following in sequelize:

<!-- ZH -->
sequelize 中的下面这段：

<!-- EN -->
```javascript
flag: { type: Sequelize.BOOLEAN, allowNull: true, defaultValue: true },
```

<!-- ZH -->
```javascript
flag: { type: Sequelize.BOOLEAN, allowNull: true, defaultValue: true },
```

<!-- EN -->
Can be achieved in TypeORM like this:

<!-- ZH -->
在 TypeORM 中可以这样实现：

<!-- EN -->
```typescript
@Column({ nullable: true, default: true })
flag: boolean;
```

<!-- ZH -->
```typescript
@Column({ nullable: true, default: true })
flag: boolean;
```

<!-- EN -->
Following in sequelize:

<!-- ZH -->
sequelize 中的下面这段：

<!-- EN -->
```javascript
flag: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }
```

<!-- ZH -->
```javascript
flag: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }
```

<!-- EN -->
Is written like this in TypeORM:

<!-- ZH -->
在 TypeORM 中这样写：

<!-- EN -->
```typescript
@Column({ default: () => "NOW()" })
myDate: Date;
```

<!-- ZH -->
```typescript
@Column({ default: () => "NOW()" })
myDate: Date;
```

<!-- EN -->
Following in sequelize:

<!-- ZH -->
sequelize 中的下面这段：

<!-- EN -->
```javascript
someUnique: { type: Sequelize.STRING, unique: true },
```

<!-- ZH -->
```javascript
someUnique: { type: Sequelize.STRING, unique: true },
```

<!-- EN -->
Can be achieved this way in TypeORM:

<!-- ZH -->
在 TypeORM 中可以这样实现：

<!-- EN -->
```typescript
@Column({ unique: true })
someUnique: string;
```

<!-- ZH -->
```typescript
@Column({ unique: true })
someUnique: string;
```

<!-- EN -->
Following in sequelize:

<!-- ZH -->
sequelize 中的下面这段：

<!-- EN -->
```javascript
fieldWithUnderscores: { type: Sequelize.STRING, field: "field_with_underscores" },
```

<!-- ZH -->
```javascript
fieldWithUnderscores: { type: Sequelize.STRING, field: "field_with_underscores" },
```

<!-- EN -->
Translates to this in TypeORM:

<!-- ZH -->
在 TypeORM 中对应：

<!-- EN -->
```typescript
@Column({ name: "field_with_underscores" })
fieldWithUnderscores: string;
```

<!-- ZH -->
```typescript
@Column({ name: "field_with_underscores" })
fieldWithUnderscores: string;
```

<!-- EN -->
Following in sequelize:

<!-- ZH -->
sequelize 中的下面这段：

<!-- EN -->
```javascript
incrementMe: { type: Sequelize.INTEGER, autoIncrement: true },
```

<!-- ZH -->
```javascript
incrementMe: { type: Sequelize.INTEGER, autoIncrement: true },
```

<!-- EN -->
Can be achieved this way in TypeORM:

<!-- ZH -->
在 TypeORM 中可以这样实现：

<!-- EN -->
```typescript
@Column()
@Generated()
incrementMe: number;
```

<!-- ZH -->
```typescript
@Column()
@Generated()
incrementMe: number;
```

<!-- EN -->
Following in sequelize:

<!-- ZH -->
sequelize 中的下面这段：

<!-- EN -->
```javascript
identifier: { type: Sequelize.STRING, primaryKey: true },
```

<!-- ZH -->
```javascript
identifier: { type: Sequelize.STRING, primaryKey: true },
```

<!-- EN -->
Can be achieved this way in TypeORM:

<!-- ZH -->
在 TypeORM 中可以这样实现：

<!-- EN -->
```typescript
@Column({ primary: true })
identifier: string;
```

<!-- ZH -->
```typescript
@Column({ primary: true })
identifier: string;
```

<!-- EN -->
To create `createDate` and `updateDate`-like columns you need to defined two columns (name it what you want) in your entity:

<!-- ZH -->
要创建类似 `createDate` 和 `updateDate` 的列，你需要在实体中定义两个列（名字随你取）：

<!-- EN -->
```typescript
@CreateDateColumn();
createDate: Date;

@UpdateDateColumn();
updateDate: Date;
```

<!-- ZH -->
```typescript
@CreateDateColumn();
createDate: Date;

@UpdateDateColumn();
updateDate: Date;
```

<!-- EN -->
### Working with models

<!-- ZH -->
### 操作模型

<!-- EN -->
To create and save a new model in sequelize you write:

<!-- ZH -->
在 sequelize 中要创建并保存一个新模型，你这样写：

<!-- EN -->
```javascript
const employee = await Employee.create({
    name: "John Doe",
    title: "senior engineer",
})
```

<!-- ZH -->
```javascript
const employee = await Employee.create({
    name: "John Doe",
    title: "senior engineer",
})
```

<!-- EN -->
In TypeORM there are several ways to create and save a new model:

<!-- ZH -->
在 TypeORM 中有几种方式可以创建并保存新模型：

<!-- EN -->
```typescript
const employee = new Employee() // you can use constructor parameters as well
employee.name = "John Doe"
employee.title = "senior engineer"
await dataSource.getRepository(Employee).save(employee)
```

<!-- ZH -->
```typescript
const employee = new Employee() // 你也可以使用构造函数参数
employee.name = "John Doe"
employee.title = "senior engineer"
await dataSource.getRepository(Employee).save(employee)
```

<!-- EN -->
or active record pattern

<!-- ZH -->
或者用 active record 模式

<!-- EN -->
```typescript
const employee = Employee.create({ name: "John Doe", title: "senior engineer" })
await employee.save()
```

<!-- ZH -->
```typescript
const employee = Employee.create({ name: "John Doe", title: "senior engineer" })
await employee.save()
```

<!-- EN -->
if you want to load an existing entity from the database and replace some of its properties you can use the following method:

<!-- ZH -->
如果你想从数据库加载一个已有实体并替换它的某些属性，可以使用以下方法：

<!-- EN -->
```typescript
const employee = await Employee.preload({ id: 1, name: "John Doe" })
```

<!-- ZH -->
```typescript
const employee = await Employee.preload({ id: 1, name: "John Doe" })
```

<!-- EN -->
Learn more about [Active Record vs Data Mapper](https://typeorm.io/docs/guides/active-record-data-mapper) and [Repository API](https://typeorm.io/docs/working-with-entity-manager/repository-api).

<!-- ZH -->
进一步了解 [Active Record 与 Data Mapper](https://typeorm.io/docs/guides/active-record-data-mapper) 和 [Repository API](https://typeorm.io/docs/working-with-entity-manager/repository-api)。

<!-- EN -->
To access properties in sequelize you do the following:

<!-- ZH -->
在 sequelize 中要访问属性，你这样做：

<!-- EN -->
```typescript
console.log(employee.get("name"))
```

<!-- ZH -->
```typescript
console.log(employee.get("name"))
```

<!-- EN -->
In TypeORM you simply do:

<!-- ZH -->
在 TypeORM 中你只需：

<!-- EN -->
```typescript
console.log(employee.name)
```

<!-- ZH -->
```typescript
console.log(employee.name)
```

<!-- EN -->
To create an index in sequelize you do:

<!-- ZH -->
在 sequelize 中要创建索引，你这样做：

<!-- EN -->
```typescript
sequelize.define(
    "user",
    {},
    {
        indexes: [
            {
                unique: true,
                fields: ["firstName", "lastName"],
            },
        ],
    },
)
```

<!-- ZH -->
```typescript
sequelize.define(
    "user",
    {},
    {
        indexes: [
            {
                unique: true,
                fields: ["firstName", "lastName"],
            },
        ],
    },
)
```

<!-- EN -->
In TypeORM you do:

<!-- ZH -->
在 TypeORM 中你这样做：

<!-- EN -->
```typescript
@Entity()
@Index(["firstName", "lastName"], { unique: true })
export class User {}
```

<!-- ZH -->
```typescript
@Entity()
@Index(["firstName", "lastName"], { unique: true })
export class User {}
```

<!-- EN -->
Learn more about [Indexes](https://typeorm.io/docs/indexes)

<!-- ZH -->
进一步了解[索引](https://typeorm.io/docs/indexes)
