-
Hi, query{
users(
where:{
Assigned_Role:{some:{user_role:{equals:"Student"}}}
},
skip:5
take:5
cursor:{user_id:5}
){
user_id
user_name
}
} Now I want to get total documents count along with pagination result. is it possible? |
Beta Was this translation helpful? Give feedback.
Replies: 17 comments 30 replies
-
Hey @aakashkag 👋 await prisma.transaction([
prisma.user.count(),
prisma.user.findMany({
take: 5,
cursor: {
id: 5,
},
}),
]) |
Beta Was this translation helpful? Give feedback.
-
Is there a solution to this problem that doesn't involve making two queries? I'm aware that you can go The only other solution I can think of is executing raw SQL but that kind of defy the purpose of using an ORM in the first place. Pagination and total document count is a trivial DB use case and should be supported by the otherwise excellent Prisma project. |
Beta Was this translation helpful? Give feedback.
-
We need a better way to get count with pagination than the accepted answer. |
Beta Was this translation helpful? Give feedback.
-
Any update for this? Hope team give us a better answer. |
Beta Was this translation helpful? Give feedback.
-
Any solution? |
Beta Was this translation helpful? Give feedback.
-
Shouldn't this topic be moved to an issue? |
Beta Was this translation helpful? Give feedback.
-
up, requested feature for me as well :) |
Beta Was this translation helpful? Give feedback.
-
Is using |
Beta Was this translation helpful? Give feedback.
-
This is really frustrating! Something like sequelize's findAndCountAll would be perfect here. |
Beta Was this translation helpful? Give feedback.
-
yo emocionado con prisma y salen con esta bobada, no entiendo que les costaba contar la bendita consulta xD |
Beta Was this translation helpful? Give feedback.
-
Would love to see this feature, my suggestion is: const products = await prisma.product.findMany({
skip: 15,
take: 3,
select: { /*...someSelections*/ }
_count:{
$total: true,
}
})
const totalProducts = products._count.$total // this should give the total results |
Beta Was this translation helpful? Give feedback.
-
this question is definitely not answered, |
Beta Was this translation helpful? Give feedback.
-
Here is my suggested workaround as of now. Let me know if anyone has any better suggestions. const getPaginatedResults = async (
sortType: string | undefined | null,
column: string,
searchQuery: string,
skip: number,
take: number,
) => {
const submission = await prisma.$transaction([
prisma.submissions.count({
where: {
[column]: {
mode: 'insensitive',
contains: searchQuery,
},
},
}),
prisma.submissions.findMany({
skip: skip,
take: take,
where: {
[column]: {
mode: 'insensitive',
contains: searchQuery,
},
},
orderBy: {
[column]: sortType ?? 'asc',
},
}),
]);
return {
total: submission[0] ?? 0,
data: submission[1],
};
}; |
Beta Was this translation helpful? Give feedback.
-
This worked for me import { Prisma } from '@prisma/client';
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
const findAll = async (userId: String) => {
const query: Prisma.categoriesFindManyArgs = {
where: {
user_id: userId,
}
};
const [categories, count] = await prisma.$transaction([
prisma.categories.findMany(query),
prisma.categories.count({ where: query.where })
]);
return {
pagination: {
total: count
},
data: categories
};
}; |
Beta Was this translation helpful? Give feedback.
-
I don't know if someone is still looking for a better solution for this, but I found a library in the Prisma documentation that gets rid of all this stuff. |
Beta Was this translation helpful? Give feedback.
-
Based on this comment in a similar issue in this repo, I wanted to share my Prisma client extension workaround for this issue, and types are inferred correcltly as well 🤞 // /src/lib/db.ts
import { Prisma, PrismaClient } from '@prisma/client'
const prisma = new PrismaClient().$extends({
name: 'findManyAndCount',
model: {
$allModels: {
findManyAndCount<Model, Args>(
this: Model,
args: Prisma.Exact<Args, Prisma.Args<Model, 'findMany'>>
): Promise<[Prisma.Result<Model, Args, 'findMany'>, number]> {
return prisma.$transaction([
(this as any).findMany(args),
(this as any).count({ where: (args as any).where })
]) as any;
}
}
}
});
export default prisma Usage: // /src/components/bookmarks.tsx
const [data, count] = await prisma.bookmark.findManyAndCount({
take: parseInt(limit) + parseInt(skip),
skip: parseInt(skip),
where: { userId: session?.user?.userId },
include: {
category: true,
tags: { include: { tag: true } },
},
orderBy: { createdAt: "desc" },
}) |
Beta Was this translation helpful? Give feedback.
-
@ndom91 The only problem with this is that it doesn't preserve the types for the regular prisma models. Solution: import { Prisma, PrismaClient } from '../client/index.js';
const findManyAndCount = {
name: 'findManyAndCount',
model: {
$allModels: {
findManyAndCount<Model, Args>(
this: Model,
args: Prisma.Exact<Args, Prisma.Args<Model, 'findMany'>>
): Promise<
[
Prisma.Result<Model, Args, 'findMany'>,
number,
Args extends { take: number } ? number : undefined
]
> {
return prisma.$transaction([
(this as any).findMany(args),
(this as any).count({ where: (args as any).where }),
]) as any;
},
},
},
};
function createExtendedClient() {
return new PrismaClient(options)
.$extends(findManyAndCount);
}
type ExtendedPrismaClient = ReturnType<typeof createExtendedClient>;
type PC = Omit<ExtendedPrismaClient, keyof PrismaClient> & PrismaClient
export const prisma = createExtendedClient() as unknown as PC; The |
Beta Was this translation helpful? Give feedback.
Hey @aakashkag 👋
You could perform this with a transaction here and return the result as per your schema: