NEST.JS框架中TypeORM的安裝和使用教程
更新時間:2025年11月22日 15:06:35 作者:江城開朗的豌豆
本文介紹了Nest.js框架及TypeORM的使用,包括環(huán)境準備、安裝步驟、TypeORM的基本查詢方法、查詢構建器以及在實際業(yè)務中的應用
前言
Nest是構建高效可擴展的 Node.js Web 應用程序的框架。 默認使用JavaScript的超集TypeScript進行開發(fā)。
環(huán)境準備
查看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 # 安裝數(shù)據(jù)庫驅動 npm install mysql2 # MySQL npm install pg # PostgreSQL
TypeORM 中常用的數(shù)據(jù)庫查詢方法
1.count()- 計數(shù)方法
基本用法
// 統(tǒng)計所有記錄
const total = await repository.count();
// 帶條件的統(tǒng)計
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'] // 關聯(lián)查詢
});3.findOne()- 查詢單條記錄
// 按ID查詢
const record = await repository.findOne(1);
// 按條件查詢
const record = await repository.findOne({
where: { title: '特定標題' }
});
// 帶關聯(lián)查詢
const record = await repository.findOne({
where: { id: 1 },
relations: ['images', 'user'],
select: ['id', 'title', 'description']
});4.findAndCount()- 查詢并計數(shù)
// 分頁查詢,同時返回數(shù)據(jù)和總數(shù)
const [records, totalCount] = await repository.findAndCount({
where: { status: 'pending' },
skip: 0,
take: 10,
order: { createdAt: 'DESC' }
});
// 返回結果:{ records: [...], total: 100 }5.create()和save()- 創(chuàng)建和保存
// 方法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. 在你的業(yè)務中的實際應用
// 上報記錄的業(yè)務查詢示例
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)
};
}
// 獲取項目統(tǒng)計
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 };
}
// 更新上報狀態(tài)
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]), // 在數(shù)組中
title: Like('%關鍵詞%') // 模糊查詢
}
});
// 范圍查詢
const records = await repository.find({
where: {
createdAt: Between(
new Date('2024-01-01'),
new Date('2024-01-31')
)
}
});總結
到此這篇關于NEST.JS框架中TypeORM的安裝和使用教程的文章就介紹到這了,更多相關TypeORM使用指南內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
mysql輸出數(shù)據(jù)賦給js變量報unterminated string literal錯誤原因
mysql 數(shù)據(jù)庫數(shù)據(jù)賦給js變量報unterminated string literal錯誤原因2010-05-05

