const users = await prisma.user.findMany({ take: 20 });
for (const u of users) {
const posts = await prisma.post.findMany({
where: { authorId: u.id },
});
console.log(u.name, posts.length);
}
21
The answer is 21. One query fetches 20 users. Then the loop awaits a separate query for each user. That is 1 + 20 = 21 queries. This is the N+1 pattern.
The code only needs the count of posts. So add include: { _count: { select: { posts: true } } } to the first query, and it gets the counts in one request.