Aegon
Aegon

Reputation: 17

How can I apply multiple filter with prisma?

I've an ecommerce project where i was working on filtering the products using prisma query.

1.) http://localhost:3000/products/[category] ---> should return all products based on catgeory

2.) http://localhost:3000/products/dress?tipe=basic&tipe=pattern&color=black&size=S ---> should return catgerory with filters applied

Prisma Query look like this

Schema

model Product {
  id         String @id @default(cuid())
  name       String
  desription String
  image      String
  price      String
  color      String
  category   String
  arrival    String
  size       String
  tipe       String
}

Query

{
      products: await prisma.product.findMany({
        where: {
          category,
          tipe: {
            in: tipe, //  [ 'pattern', 'hoodie', 'zipper' ] get from searchParams
          },
          color:{
            in: color
          },
          size: {
            in: size
          }
        },
      }),
    }

But the query return []

Not sure why this query not works! Please help.

Upvotes: 0

Views: 787

Answers (1)

Raphael Etim
Raphael Etim

Reputation: 813

You can achieve this by dynamically constructing the where clause in findMany query. So in your API you can check the query parameters which are obtained and based on that construct the clause. For Example you can do something like this:

 const where = {
   tipe: 'basic'
  };

  if(params.colour){
    where.colour = params.colour
  }

  if(params.size){
    where.size = params.size
  }

  const results = await prisma.product.findMany({
    where,
  });

Upvotes: 1

Related Questions