快速开始
TypeORM 是一个 ORM,可运行在 Node.js、Browser、Cordova、Ionic、React Native、NativeScript、Expo 和 Electron 平台上,并可与 TypeScript 和 JavaScript(ES2023)一起使用。
它的目标是始终支持最新的 JavaScript 特性,并提供额外的能力,帮助你开发任何类型的数据库应用——从只有几张表的小型应用,到使用多个数据库的大型企业级应用。
TypeORM 支持的数据库比任何其他 JS/TS ORM 都多:Google Spanner、Microsoft SqlServer、MongoDB、MySQL/MariaDB、Oracle、Postgres、SAP HANA 和 SQLite,以及各类衍生数据库与不同驱动。
与目前存在的所有其他 JavaScript ORM 不同,TypeORM 同时支持 Active Record 和 Data Mapper 两种模式,这意味着你可以用最高的效率编写高质量、松耦合、可扩展、易维护的应用。
TypeORM 深受其他 ORM 的影响,例如 Hibernate、Doctrine 和 Entity Framework。
特性
- 同时支持 DataMapper 与 ActiveRecord(由你选择)。
- 实体与列。
- 数据库专属的列类型。
- Entity Manager。
- Repository 与自定义仓储。
- 清晰的对象关系模型。
- 关联(关系)。
- 急加载与懒加载关系。
- 单向、双向与自引用关系。
- 支持多种继承模式。
- 级联。
- 索引。
- 事务。
- 支持自动生成的迁移。
- 连接池。
- 复制。
- 使用多个数据库实例。
- 同时使用多种数据库类型。
- 跨数据库与跨模式查询。
- 语法优雅、灵活而强大的 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。
还有更多……
使用 TypeORM 时,你的模型长这样:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
age: number
}你的领域逻辑长这样:
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)或者,如果你更倾向于使用 ActiveRecord 实现,也可以这样用:
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
}此时你的领域逻辑会变成这样:
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()安装
安装 npm 包:
npm install typeorm你需要安装
reflect-metadata垫片:npm install reflect-metadata并在应用的全局位置引入它(例如在
app.ts中):import "reflect-metadata"你可能还需要安装 node 的类型声明:
npm install @types/node --save-dev安装数据库驱动:参见各驱动的文档:mongodb、mssql、mysql/mariadb、oracle、postgres、sap、spanner、sqlite。
TypeScript 配置
另外,请确保你使用的 TypeScript 版本为 4.5 或更高,并在 tsconfig.json 中启用以下配置:
"emitDecoratorMetadata": true,
"experimentalDecorators": true,快速上手
上手 TypeORM 最快的方式是用它的 CLI 命令生成一个起始项目。快速上手仅在你将 TypeORM 用于 Node.js 应用时可用。如果你使用其他平台,请继续阅读分步指南。
使用 CLI 创建新项目,运行以下命令:
npx typeorm init --name MyProject --database postgres其中 name 是项目名称,database 是你要使用的数据库。数据库可以是以下值之一:mysql、mariadb、postgres、cockroachdb、sqlite、mssql、sap、spanner、oracle、mongodb、cordova、react-native、expo、nativescript。
该命令会在 MyProject 目录下生成一个新项目,包含以下文件:
MyProject
├── src // 存放 TypeScript 代码的位置
│ ├── entities // 存放实体(数据库模型)的位置
│ │ └── User.ts // 示例实体
│ ├── migrations // 存放迁移的位置
│ ├── data-source.ts // 数据源与全部连接配置
│ └── index.ts // 应用入口
├── .gitignore // 标准 gitignore 文件
├── package.json // node 模块依赖
├── README.md // 简单的 readme 文件
└── tsconfig.json // TypeScript 编译选项你也可以在已有的 node 项目上运行
typeorm init,但要小心——它可能会覆盖你已有的某些文件。
下一步是安装新项目的依赖:
cd MyProject
npm install依赖全部安装完成后,编辑 data-source.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: [],
})通常情况下,你只需要配置 host、username、password、database,也许还有 port 这几项。
配置完成且所有 node 模块都已安装后,就可以运行你的应用了:
npm start就这样,你的应用应该能成功运行,并向数据库中插入一条新用户记录。你可以继续在这个项目上工作,集成你需要的其他模块,并开始创建更多实体。
运行
npx typeorm init --name MyProject --database postgres --module esm命令可以生成 ESM 项目。
运行
npx typeorm init --name MyProject --database mysql --express命令可以生成一个更高级的、已装好 express 的项目。
运行
npx typeorm init --name MyProject --database postgres --docker命令可以生成 docker-compose 文件。
分步指南
你对 ORM 的期待是什么?首先,你期待它为你创建数据库表,并且不必痛苦地编写大量难以维护的 SQL 查询就能查找 / 插入 / 更新 / 删除数据。本指南将向你展示如何从零搭建 TypeORM,并让它做到你对 ORM 的这些期待。
创建模型
与数据库打交道从创建表开始。你怎么告诉 TypeORM 去创建一张数据库表?答案是——通过模型。你应用中的模型就是你的数据库表。
例如,你有一个 Photo 模型:
export class Photo {
id: number
name: string
description: string
filename: string
views: number
isPublished: boolean
}你想把照片存进数据库。要把东西存进数据库,首先你需要一张数据库表,而数据库表是由你的模型创建的。不是所有模型都会建表,只有那些被你定义为实体的模型才会。
创建实体
实体是被 @Entity 装饰器修饰的模型。TypeORM 会为这类模型创建数据库表。在 TypeORM 中你到处都在和实体打交道。你可以加载 / 插入 / 更新 / 删除它们,并对其执行其他操作。
把我们的 Photo 模型变成实体:
import { Entity } from "typeorm"
@Entity()
export class Photo {
id: number
name: string
description: string
filename: string
views: number
isPublished: boolean
}现在,TypeORM 会为 Photo 实体创建一张数据库表,我们就能在应用的任何地方使用它了。我们已经创建了一张数据库表,可是哪张表能没有列呢?接下来给这张表加几列。
添加表列
要添加数据库列,你需要用 @Column 装饰器修饰实体上那些你想变成列的属性。
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
}现在 id、name、description、filename、views 和 isPublished 这些列会被添加到 photo 表中。数据库中的列类型由你使用的属性类型推断得出,例如 number 会被转换成 integer,string 转换成 varchar,boolean 转换成 bool 等。不过你也可以在 @Column 装饰器中显式指定列类型,从而使用数据库支持的任意列类型。
我们已经生成了一张带列的数据库表,但还剩一件事。每张数据库表都必须有一列作为主键。
创建主键列
每个实体 必须 至少有一列主键。这是硬性要求,无法回避。要把某一列变成主键,你需要使用 @PrimaryColumn 装饰器。
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
}创建自增列
现在,假设你希望 id 列自动生成(也就是所谓的自增 / 序列 / serial / 生成标识列)。要做到这一点,你需要把 @PrimaryColumn 装饰器换成 @PrimaryGeneratedColumn 装饰器:
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
}列数据类型
接下来,我们来修正数据类型。默认情况下,string 会被映射为类似 varchar(255) 的类型(取决于数据库类型),number 会被映射为类似 integer 的类型(同样取决于数据库类型)。我们不希望所有列都被限制成 varchar 或 integer。来设置正确的数据类型:
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
}列类型是数据库专属的。你可以设置数据库支持的任何列类型。关于受支持的列类型的更多信息可以在这里找到。
创建新的 DataSource
现在实体已经创建好了,我们来创建 index.ts 文件,并在其中配置 DataSource:
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)
}本例中使用的是 Postgres,但你可以使用任何其他受支持的数据库。要换用其他数据库,把配置项中的 type 改成你正在使用的数据库类型即可:mysql、mariadb、postgres、cockroachdb、sqlite、mssql、oracle、sap、spanner、cordova、nativescript、react-native、expo 或 mongodb。同时请确保使用你自己的 host、port、username、password 和 database 配置。
我们把 Photo 实体加入了该数据源的实体列表。你在连接中用到的每个实体都必须列在那里。
设置 synchronize 可以确保每次运行应用时,你的实体都会与数据库保持同步。
运行应用
现在如果你运行 index.ts,与数据库的连接就会被初始化,并为你创建一张存放照片的数据库表。
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(100) | |
| description | text | |
| filename | varchar(255) | |
| views | int | |
| isPublished | boolean | |
+-------------+--------------+----------------------------+创建一张照片并插入数据库
现在我们来创建一张新照片并把它存进数据库:
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)实体保存后会获得一个新生成的 id。save 方法返回的是你传给它的那个对象实例。它不是该对象的新副本,而是修改了它的 "id" 之后把它返回。
使用 Entity Manager
我们刚刚创建了一张新照片并把它存进了数据库,用的是 EntityManager。借助 Entity Manager,你可以操作应用中的任何实体。例如,我们来加载刚才保存的实体:
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"
const savedPhotos = await AppDataSource.manager.find(Photo)
console.log("All photos from the db: ", savedPhotos)savedPhotos 将是一个 Photo 对象数组,其中的数据来自数据库。
进一步了解 EntityManager。
使用 Repository
现在我们重构一下代码,用 Repository 代替 EntityManager。每个实体都有自己的 repository,负责处理与该实体相关的所有操作。当你经常和实体打交道时,Repository 比 EntityManager 用起来更方便:
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)在这里进一步了解 Repository。
从数据库加载
我们再用 Repository 试试更多的加载操作:
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)在数据库中更新
现在我们从数据库加载一张照片,更新它,再保存回去:
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)现在数据库中 id = 1 的那张照片就被更新了。
从数据库删除
现在我们把照片从数据库中删除:
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)现在数据库中 id = 1 的那张照片就被删除了。
创建一对一关系
我们来和另一个类创建一对一关系。在 PhotoMetadata.ts 中新建一个类。这个 PhotoMetadata 类用来存放照片的额外元信息:
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
}这里我们用了一个新的装饰器 @OneToOne。它让我们能在两个实体之间建立一对一关系。我们还加上了 @JoinColumn 装饰器,它表示关系的这一方将拥有该关系。关系可以是单向的,也可以是双向的。关系只有一方能成为拥有方。在关系的拥有方上必须使用 @JoinColumn 装饰器。
运行应用后,你会看到一张新生成的表,其中包含一个指向 photo 关系的外键列:
+-------------+--------------+----------------------------+
| photo_metadata |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| height | int | |
| width | int | |
| comment | varchar(255) | |
| compressed | boolean | |
| orientation | varchar(255) | |
| photoId | int | FOREIGN KEY |
+-------------+--------------+----------------------------+保存一对一关系
现在我们保存一张照片及其元数据,并把它们关联起来。
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",
)关系的反向方
关系可以是单向的,也可以是双向的。目前 PhotoMetadata 与 Photo 之间的关系是单向的。关系的拥有方是 PhotoMetadata,而 Photo 对 PhotoMetadata 一无所知。这使得从 Photo 一侧访问 PhotoMetadata 变得很麻烦。要解决这个问题,我们应该加一个反向关系,让 PhotoMetadata 与 Photo 之间的关系变成双向的。我们来修改实体:
import {
Entity,
Column,
PrimaryGeneratedColumn,
OneToOne,
JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"
@Entity()
export class PhotoMetadata {
/* ... 其他列 */
@OneToOne(() => Photo, (photo) => photo.metadata)
@JoinColumn()
photo: Photo
}import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"
@Entity()
export class Photo {
/* ... 其他列 */
@OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
metadata: PhotoMetadata
}photo => photo.metadata 是一个返回关系反向方名称的函数。这里我们表明,Photo 类的 metadata 属性就是我们在 Photo 类中存放 PhotoMetadata 的地方。除了传入一个返回 photo 属性的函数,你也可以给 @OneToOne 装饰器传一个字符串,比如 "metadata"。不过我们采用这种函数式写法,是为了让重构更容易。
注意,@JoinColumn 装饰器只能在关系的一侧使用。你把该装饰器放在哪一侧,哪一侧就是关系的拥有方。关系的拥有方在数据库中持有带外键的那一列。
ESM 项目中的关系
如果你的 TypeScript 项目使用 ESM,那么在关系属性上应使用 Relation 包装类型,以避免循环依赖问题。我们来修改实体:
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>
}import {
Entity,
Column,
PrimaryGeneratedColumn,
OneToOne,
Relation,
} from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"
@Entity()
export class Photo {
/* ... 其他列 */
@OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
metadata: Relation<PhotoMetadata>
}加载对象及其关系
现在我们用一条查询加载照片及其照片元数据。有两种方式可以做到——使用 find* 方法,或者使用 QueryBuilder 功能。我们先用 find* 方法。find* 方法允许你传入一个符合 FindOneOptions / FindManyOptions 接口的对象。
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,
},
})这里,photos 会包含一个来自数据库的照片数组,并且每张照片都带有它的照片元数据。在这份文档中进一步了解 Find Options。
使用查找选项很好而且极其简单,但如果你需要更复杂的查询,就该改用 QueryBuilder。QueryBuilder 能让你优雅地写出更复杂的查询:
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()QueryBuilder 几乎可以创建并执行任意复杂度的 SQL 查询。使用 QueryBuilder 时,请把自己想象成正在编写一条 SQL 查询。在这个例子中,"photo" 和 "metadata" 是应用在被选中照片上的别名。你通过别名来访问被选中数据的列和属性。
使用级联自动保存关联对象
当我们希望在保存某个对象时自动保存其关联对象,就可以在关系上配置级联选项。我们稍微改一下 Photo 的 @OneToOne 装饰器:
export class Photo {
// ... 其他列
@OneToOne(() => PhotoMetadata, (metadata) => metadata.photo, {
cascade: true,
})
metadata: PhotoMetadata
}使用 cascade 之后,我们就不必再分别保存照片和元数据对象了。现在我们只需保存照片对象,得益于级联选项,元数据对象会被自动保存。
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.")注意,现在我们设置的是照片的 metadata 属性,而不是像之前那样设置元数据的 photo 属性。只有当你从照片一侧把照片和它的元数据关联起来时,cascade 特性才会生效。如果你设置的是元数据一侧,元数据不会被自动保存。
创建多对一 / 一对多关系
我们来创建一个多对一 / 一对多关系。假设一张照片有一位作者,而每位作者可以有多张照片。首先,创建一个 Author 类:
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[]
}Author 持有关系的反向方。OneToMany 永远是关系的反向方,它不能脱离关系另一侧的 ManyToOne 单独存在。
现在把关系的拥有方加进 Photo 实体:
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
}在多对一 / 一对多关系中,拥有方永远是多对一方。也就是说,使用 @ManyToOne 的那个类会存放关联对象的 id。
运行应用后,ORM 会创建 author 表:
+-------------+--------------+----------------------------+
| author |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(255) | |
+-------------+--------------+----------------------------+它还会修改 photo 表,新增一个 author 列并为其创建外键:
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(255) | |
| description | varchar(255) | |
| filename | varchar(255) | |
| isPublished | boolean | |
| authorId | int | FOREIGN KEY |
+-------------+--------------+----------------------------+创建多对多关系
我们来创建一个多对多关系。假设一张照片可以出现在多个相册中,而每个相册可以包含多张照片。创建一个 Album 类:
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[]
}必须使用 @JoinTable 来指明这一侧是关系的拥有方。
现在把关系的反向方加到 Photo 类中:
export class Photo {
// ... 其他列
@ManyToMany(() => Album, (album) => album.photos)
albums: Album[]
}运行应用后,ORM 会创建一张 album_photos_photo_albums 中间表:
+-------------+--------------+----------------------------+
| album_photos_photo_albums |
+-------------+--------------+----------------------------+
| album_id | int | PRIMARY KEY FOREIGN KEY |
| photo_id | int | PRIMARY KEY FOREIGN KEY |
+-------------+--------------+----------------------------+别忘了在 ORM 中把 Album 类注册到你的连接里:
const options: DataSourceOptions = {
// ... 其他选项
entities: [Photo, PhotoMetadata, Author, Album],
}现在我们把相册和照片插入数据库:
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,
},
})loadedPhoto 将等于:
{
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"
}]
}使用 QueryBuilder
你可以用 QueryBuilder 构建几乎任意复杂度的 SQL 查询。例如,你可以这样做:
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()这条查询会选出所有已发布、且名称为 "My" 或 "Mishka" 的照片。它会从第 5 条位置开始选取(分页偏移量),并且只选取 10 条结果(分页限制)。选取结果按 id 降序排列。照片的相册会被左连接,其元数据会被内连接。
你会在应用中大量使用 query builder。在这里进一步了解 QueryBuilder。
扩展
有若干扩展可以简化 TypeORM 的使用,并把它与其他模块集成:
- 从已有数据库生成模型 - typeorm-model-generator
- 夹具(fixtures)加载器 - typeorm-fixtures-cli
- ER 图生成器 - typeorm-uml
- 另一个 ER 图生成器 - erdia
- 创建、删除并填充数据库种子数据 - typeorm-extension
- 生成迁移/实体后自动更新
data-source.ts- typeorm-codebase-sync - 便捷操作
relations对象 - typeorm-relations - 基于 GraphQL 查询自动生成
relations- typeorm-relations-graphql
贡献
本项目得以存在,要感谢所有做出贡献的人:
赞助者
开源既困难又耗时。如果你愿意为 TypeORM 的未来投资,可以成为赞助者,让我们的核心团队把更多时间花在 TypeORM 的改进与新特性上。成为赞助者
金牌赞助者
成为金牌赞助者,可获得我们核心贡献者提供的优质技术支持。成为金牌赞助者
TypeORM is an ORM 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).
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.
TypeORM supports more databases than any other JS/TS ORM: Google Spanner, Microsoft SqlServer, MongoDB, MySQL/MariaDB, Oracle, Postgres, SAP HANA and SQLite, as well as derived databases and different drivers.
TypeORM supports both Active Record and Data Mapper 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.
TypeORM is highly influenced by other ORMs, such as Hibernate, Doctrine and Entity Framework.
Features
- Supports both DataMapper and ActiveRecord (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 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.
And more...
With TypeORM, your models look like this:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
firstName: string
@Column()
lastName: string
@Column()
age: number
}And your domain logic looks like this:
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)Alternatively, if you prefer to use the ActiveRecord implementation, you can use it as well:
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
}And your domain logic will look this way:
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()Installation
Install the npm package:
npm install typeormYou need to install
reflect-metadatashim:npm install reflect-metadataand import it somewhere in the global place of your app (for example in
app.ts):import "reflect-metadata"You may need to install node typings:
npm install @types/node --save-devInstall a database driver: see the documentation for each particular driver: mongodb, mssql, mysql/mariadb, oracle, postgres, sap, spanner, sqlite.
TypeScript configuration
Also, make sure you are using TypeScript version 4.5 or higher, and you have enabled the following settings in tsconfig.json:
"emitDecoratorMetadata": true,
"experimentalDecorators": true,Quick Start
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.
To create a new project using CLI, run the following command:
npx typeorm init --name MyProject --database postgresWhere 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.
This command will generate a new project in the MyProject directory with the following files:
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 optionsYou can also run
typeorm initon an existing node project, but be careful - it may override some files you already have.
The next step is to install new project dependencies:
cd MyProject
npm installAfter you have all dependencies installed, edit the data-source.ts file and put your own database connection configuration options in there:
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: [],
})Particularly, most of the time you'll only need to configure host, username, password, database and maybe port options.
Once you finish with configuration and all node modules are installed, you can run your application:
npm startThat'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.
You can generate an ESM project by running
npx typeorm init --name MyProject --database postgres --module esmcommand.
You can generate an even more advanced project with express installed by running
npx typeorm init --name MyProject --database mysql --expresscommand.
You can generate a docker-compose file by running
npx typeorm init --name MyProject --database postgres --dockercommand.
Step-by-Step Guide
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.
Create a model
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.
For example, you have a Photo model:
export class Photo {
id: number
name: string
description: string
filename: string
views: number
isPublished: boolean
}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.
Create an entity
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.
Let's make our Photo model an entity:
import { Entity } from "typeorm"
@Entity()
export class Photo {
id: number
name: string
description: string
filename: string
views: number
isPublished: boolean
}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.
Adding table columns
To add database columns, you need to decorate an entity's properties you want to make into a column with a @Column decorator.
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
}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.
We generated a database table with columns, but there is one thing left. Each database table must have a column with a primary key.
Creating a primary column
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.
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
}Creating an auto-generated column
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:
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
}Column data types
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:
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
}Column types are database-specific. You can set any column type your database supports. More information on supported column types can be found here.
Creating a new DataSource
Now, when our entity is created, let's create index.ts file and set up our DataSource there:
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)
}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.
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.
Setting synchronize makes sure your entities will be synced with the database, every time you run the application.
Running the application
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.
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(100) | |
| description | text | |
| filename | varchar(255) | |
| views | int | |
| isPublished | boolean | |
+-------------+--------------+----------------------------+Creating and inserting a photo into the database
Now let's create a new photo to save it in the database:
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)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.
Using Entity Manager
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:
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"
const savedPhotos = await AppDataSource.manager.find(Photo)
console.log("All photos from the db: ", savedPhotos)savedPhotos will be an array of Photo objects with the data loaded from the database.
Learn more about EntityManager.
Using Repositories
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:
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)Learn more about Repository here.
Loading from the database
Let's try more load operations using the Repository:
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)Updating in the database
Now let's load a single photo from the database, update it, and save it:
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)Now photo with id = 1 will be updated in the database.
Removing from the database
Now let's remove our photo from the database:
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)Now photo with id = 1 will be removed from the database.
Creating a one-to-one relation
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:
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
}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.
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:
+-------------+--------------+----------------------------+
| photo_metadata |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| height | int | |
| width | int | |
| comment | varchar(255) | |
| compressed | boolean | |
| orientation | varchar(255) | |
| photoId | int | FOREIGN KEY |
+-------------+--------------+----------------------------+Save a one-to-one relation
Now let's save a photo and its metadata and attach them to each other.
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",
)Inverse side of the relationship
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:
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
}import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"
@Entity()
export class Photo {
/* ... other columns */
@OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
metadata: PhotoMetadata
}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.
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.
Relations in ESM projects
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:
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>
}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>
}Loading objects with their relations
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.
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,
},
})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.
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:
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()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.
Using cascades to automatically save related objects
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:
export class Photo {
// ... other columns
@OneToOne(() => PhotoMetadata, (metadata) => metadata.photo, {
cascade: true,
})
metadata: PhotoMetadata
}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.
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.")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.
Creating a many-to-one / one-to-many relation
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:
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[]
}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.
Now let's add the owner side of the relation into the Photo entity:
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
}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.
After you run the application, the ORM will create the author table:
+-------------+--------------+----------------------------+
| author |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(255) | |
+-------------+--------------+----------------------------+It will also modify the photo table, adding a new author column and creating a foreign key for it:
+-------------+--------------+----------------------------+
| photo |
+-------------+--------------+----------------------------+
| id | int | PRIMARY KEY AUTO_INCREMENT |
| name | varchar(255) | |
| description | varchar(255) | |
| filename | varchar(255) | |
| isPublished | boolean | |
| authorId | int | FOREIGN KEY |
+-------------+--------------+----------------------------+Creating a many-to-many relation
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:
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[]
}@JoinTable is required to specify that this is the owner side of the relationship.
Now let's add the inverse side of our relation to the Photo class:
export class Photo {
// ... other columns
@ManyToMany(() => Album, (album) => album.photos)
albums: Album[]
}After you run the application, the ORM will create an album_photos_photo_albums junction table:
+-------------+--------------+----------------------------+
| album_photos_photo_albums |
+-------------+--------------+----------------------------+
| album_id | int | PRIMARY KEY FOREIGN KEY |
| photo_id | int | PRIMARY KEY FOREIGN KEY |
+-------------+--------------+----------------------------+Remember to register the Album class with your connection in the ORM:
const options: DataSourceOptions = {
// ... other options
entities: [Photo, PhotoMetadata, Author, Album],
}Now let's insert albums and photos into our database:
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,
},
})loadedPhoto will be equal to:
{
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"
}]
}Using QueryBuilder
You can use QueryBuilder to build SQL queries of almost any complexity. For example, you can do this:
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()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.
You'll use the query builder in your application a lot. Learn more about QueryBuilder here.
Extensions
There are several extensions that simplify working with TypeORM and integrating it with other modules:
- Models generation from the existing database - typeorm-model-generator
- Fixtures loader - typeorm-fixtures-cli
- ER Diagram generator - typeorm-uml
- another ER Diagram generator - erdia
- Create, drop and seed database - typeorm-extension
- Automatically update
data-source.tsafter generating migrations/entities - typeorm-codebase-sync - Easy manipulation of
relationsobjects - typeorm-relations - Automatically generate
relationsbased on a GraphQL query - typeorm-relations-graphql
Contributing
Learn about contribution here and how to set up your development environment here.
This project exists thanks to all the people who contribute:
Sponsors
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
Gold Sponsors
Become a gold sponsor and get premium technical support from our core contributors. Become a gold sponsor