Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prisma find many and count in one request

I have a pagination in my category service, and I have to return obj with total count of categories and data

But there's can be some parameters. As example, I should return categories that was created by certain user:

async findAll(
    { onlyParents }: ParamsCategoryDto,
    user: ITokenPayload | undefined,
): Promise<IFilterRes> {
    const categories = await this.prisma.category.findMany({
      where: {
        user_id: user?.id,
      },
    });

    return {
      pagination: {
        total: this.prisma.category.count({
          where: { // <- duplicate
          user_id: user?.id,
        },
      }),
    },
    data: categories,
  };
}

I should duplicate where in both query. Which is not very nice. Is there any option to do it in one request.

P.S. I can make some var for where, but in this way I lose typification, which I also don't like.

like image 546
SPR1NG Avatar asked Dec 12 '25 06:12

SPR1NG


1 Answers

This is my example code to acheive it with a single transaction, no duplicate code and not losing type autocomplete

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
  };
};

like image 119
Hoàng Huy Khánh Avatar answered Dec 14 '25 20:12

Hoàng Huy Khánh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!