[ PROMPT_NODE_23760 ]
数据库模式
[ SKILL_DOCUMENTATION ]
# 数据库模式 - Prisma 最佳实践
后端微服务中使用 Prisma 进行数据库访问的完整指南。
## 目录
- [PrismaService 使用](#prismaservice-使用)
- [仓库模式](#仓库模式)
- [事务模式](#事务模式)
- [查询优化](#查询优化)
- [N+1 查询预防](#n+1-查询预防)
- [错误处理](#错误处理)
---
## PrismaService 使用
### 基本模式
typescript
import { PrismaService } from '@project-lifecycle-portal/database';
// 始终使用 PrismaService.main
const users = await PrismaService.main.user.findMany();
### 检查可用性
typescript
if (!PrismaService.isAvailable) {
throw new Error('Prisma client not initialized');
}
const user = await PrismaService.main.user.findUnique({ where: { id } });
---
## 仓库模式
### 为什么使用仓库模式
✅ **在以下情况使用仓库:**
- 包含复杂查询(joins/includes)
- 查询在多处重复使用
- 需要缓存层
- 需要为测试进行 Mock
❌ **在以下情况跳过仓库:**
- 简单的单次查询
- 原型开发(后续可重构)
### 仓库模板
typescript
export class UserRepository {
async findById(id: string): Promise {
return PrismaService.main.user.findUnique({
where: { id },
include: { profile: true },
});
}
async findActive(): Promise {
return PrismaService.main.user.findMany({
where: { isActive: true },
orderBy: { createdAt: 'desc' },
});
}
async create(data: Prisma.UserCreateInput): Promise {
return PrismaService.main.user.create({ data });
}
}
---
## 事务模式
### 简单事务
typescript
const result = await PrismaService.main.$transaction(async (tx) => {
const user = await tx.user.create({ data: userData });
const profile = await tx.userProfile.create({ data: { userId: user.id } });
return { user, profile };
});
### 交互式事务
typescript
const result = await PrismaService.main.$transaction(
async (tx) => {
const user = await tx.user.findUnique({ where: { id } });
if (!user) throw new Error('User not found');
return await tx.user.update({
where: { id },
data: { lastLogin: new Date() },
});
},
{
maxWait: 5000,
timeout: 10000,
}
);
---
## 查询优化