From 3fa50e79f12fe2b66ebd5d643ed597c6a121b198 Mon Sep 17 00:00:00 2001 From: muqiuhan Date: Sat, 3 May 2025 10:47:05 +0000 Subject: deploy: a0dad147ccf1d831c5f48d8d0e868160a23cc92c --- .../04/02/N-1-selects-problem-\344\270\216-Prisma-ORM/index.html" | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to '2025/04/02') diff --git "a/2025/04/02/N-1-selects-problem-\344\270\216-Prisma-ORM/index.html" "b/2025/04/02/N-1-selects-problem-\344\270\216-Prisma-ORM/index.html" index 2df41efe..ac98e832 100644 --- "a/2025/04/02/N-1-selects-problem-\344\270\216-Prisma-ORM/index.html" +++ "b/2025/04/02/N-1-selects-problem-\344\270\216-Prisma-ORM/index.html" @@ -211,7 +211,7 @@

Prisma ORM 在设计上就考虑了 N+1 问题,并提供了一种既方便开发者又高效的解决方案。当使用 Prisma Client 查询数据并需要包含关联模型时,Prisma 会自动优化查询,避免产生 N+1 查询,主要通过关系查询(Relation Queries)中的 include 选项或嵌套读取(nested reads)来实现这一点:

假设想获取所有用户及其发布的帖子,使用 Prisma Client,可以这样写:

-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function getUsersWithPosts() {
const usersWithPosts = await prisma.user.findMany({
include: {
posts: true, // 指示 Prisma 加载关联的 posts
},
})
// usersWithPosts 包含了用户列表,每个用户对象中都有一个 posts 数组
console.log(usersWithPosts)
}

getUsersWithPosts()
.catch((e) => {
throw e
})
.finally(async () => {
await prisma.$disconnect()
})
+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function getUsersWithPosts() {
const usersWithPosts = await prisma.user.findMany({
include: {
posts: true, // 指示 Prisma 加载关联的 posts
},
})
// usersWithPosts 包含了用户列表,每个用户对象中都有一个 posts 数组
console.log(usersWithPosts)
}

getUsersWithPosts()
.catch((e) => {
throw e
})
.finally(async () => {
await prisma.$disconnect()
})

当执行上述查询时,Prisma 不会 生成 N+1 个 SQL 查询。而是首先会分析请求,并将其转化为数量非常有限的高效 SQL 查询。对于上面这个一对多关系的 include 查询,Prisma 通常会执行以下两步(类似于批量加载策略):

    @@ -234,6 +234,11 @@