NEST.JS框架中TypeORM的安装和使用教程
作者:江城开朗的豌豆
本文介绍了Nest.js框架及TypeORM的使用,包括环境准备、安装步骤、TypeORM的基本查询方法、查询构建器以及在实际业务中的应用
前言
Nest是构建高效可扩展的 Node.js Web 应用程序的框架。 默认使用JavaScript的超集TypeScript进行开发。
环境准备
查看node和npm版本:
$ node --version v10.11.0 $ npm --version 6.5.0
安装@nestjs/cli
使用npm全局安装@nestjs/cli:
$ npm i -g @nestjs/cli /usr/local/bin/nest -> /usr/local/lib/node_modules/@nestjs/cli/bin/nest.js + @nestjs/cli@5.7.1 added 11 packages from 6 contributors, removed 27 packages and updated 12 packages in 10.322s
使用nest --version命令查看nest当前版本:
$ nest --version 5.7.1
TypeORM安装
TypeORM无疑是 node.js 世界中最成熟的对象关系映射器(ORM )。由于它是用 TypeScript 编写的,所以它在 Nest 框架下运行得非常好
npm install typeorm reflect-metadata @types/node # 安装数据库驱动 npm install mysql2 # MySQL npm install pg # PostgreSQL
TypeORM 中常用的数据库查询方法
1.count()- 计数方法
基本用法
// 统计所有记录
const total = await repository.count();
// 带条件的统计
const completedCount = await repository.count({
where: { completed: true }
});
// 多个条件
const count = await repository.count({
where: {
status: 'pending',
userId: 1
}
});2.find()- 查询多条记录
基本查询
// 查询所有记录
const allRecords = await repository.find();
// 带条件查询
const pendingRecords = await repository.find({
where: { status: 'pending' }
});
// 多个条件(AND)
const records = await repository.find({
where: {
status: 'pending',
userId: 1
}
});
// 或条件(OR)
const records = await repository.find({
where: [
{ status: 'pending' },
{ status: 'in-progress' }
]
});复杂查询选项
const records = await repository.find({
select: ['id', 'title', 'createdAt'], // 选择特定字段
where: { status: 'pending' },
order: { createdAt: 'DESC' }, // 排序
skip: 10, // 跳过前10条
take: 20, // 取20条
relations: ['images', 'user'] // 关联查询
});3.findOne()- 查询单条记录
// 按ID查询
const record = await repository.findOne(1);
// 按条件查询
const record = await repository.findOne({
where: { title: '特定标题' }
});
// 带关联查询
const record = await repository.findOne({
where: { id: 1 },
relations: ['images', 'user'],
select: ['id', 'title', 'description']
});4.findAndCount()- 查询并计数
// 分页查询,同时返回数据和总数
const [records, totalCount] = await repository.findAndCount({
where: { status: 'pending' },
skip: 0,
take: 10,
order: { createdAt: 'DESC' }
});
// 返回结果:{ records: [...], total: 100 }5.create()和save()- 创建和保存
// 方法1:create + save
const newRecord = repository.create({
title: '新标题',
description: '描述内容',
userId: 1
});
await repository.save(newRecord);
// 方法2:直接 save
await repository.save({
title: '新标题',
description: '描述内容',
userId: 1
});
// 批量保存
await repository.save([
{ title: '标题1', userId: 1 },
{ title: '标题2', userId: 1 }
]);6.update()- 更新记录
// 按条件更新
await repository.update(
{ status: 'pending' }, // 条件
{ status: 'completed' } // 更新内容
);
// 按ID更新
await repository.update(1, {
title: '新标题',
completed: true
});
// 批量更新
await repository.update(
{ userId: 1 },
{ priority: 2 }
);7.delete()- 删除记录
// 按ID删除
await repository.delete(1);
// 按条件删除
await repository.delete({
status: 'completed'
});
// 批量删除
await repository.delete([1, 2, 3]);8. 查询构建器 (Query Builder)
// 复杂查询
const records = await repository
.createQueryBuilder('report')
.leftJoinAndSelect('report.images', 'image')
.leftJoinAndSelect('report.user', 'user')
.where('report.status = :status', { status: 'pending' })
.andWhere('report.userId = :userId', { userId: 1 })
.orderBy('report.createdAt', 'DESC')
.skip(0)
.take(10)
.getMany();
// 原生SQL查询
const records = await repository
.createQueryBuilder('report')
.where('DATE(created_at) = :date', { date: '2024-01-01' })
.getMany();9. 在你的业务中的实际应用
// 上报记录的业务查询示例
export class ProblemReportService {
// 获取用户的上报记录
async getUserReports(userId: number, page: number = 1, limit: number = 10) {
const [reports, total] = await this.problemReportRepository.findAndCount({
where: { userId },
relations: ['images', 'project'],
order: { createdAt: 'DESC' },
skip: (page - 1) * limit,
take: limit
});
return {
reports,
total,
page,
totalPages: Math.ceil(total / limit)
};
}
// 获取项目统计
async getProjectStats(projectId: number) {
const total = await this.problemReportRepository.count({
where: { projectId }
});
const byStatus = await this.problemReportRepository
.createQueryBuilder('report')
.select('report.status, COUNT(*) as count')
.where('report.projectId = :projectId', { projectId })
.groupBy('report.status')
.getRawMany();
return { total, byStatus };
}
// 更新上报状态
async updateReportStatus(id: number, status: number) {
await this.problemReportRepository.update(id, { status });
return this.problemReportRepository.findOne(id);
}
}10. 常用查询条件运算符
// 比较运算符
const records = await repository.find({
where: {
priority: MoreThan(2), // 大于
createdAt: LessThan(new Date()), // 小于
userId: In([1, 2, 3]), // 在数组中
title: Like('%关键词%') // 模糊查询
}
});
// 范围查询
const records = await repository.find({
where: {
createdAt: Between(
new Date('2024-01-01'),
new Date('2024-01-31')
)
}
});总结
到此这篇关于NEST.JS框架中TypeORM的安装和使用教程的文章就介绍到这了,更多相关TypeORM使用指南内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
