34

I am using Prisma with NextJs.

In my API, I send to the back end a list of numbers that correspond to id's of objects in my database.

As an example, if I receive the list [1, 2, 12], I would like to return the objects where the id is either 1, 2 or 12

This is part of a query that is more complex ( sorting / counting / ... ) but I am blocking at the first step with is to get the list of elements

So far I have this :

import { PrismaClient, Prisma } from '@prisma/client'

const prisma = new PrismaClient()


export default async function handler(req, res) {
    if (req.method !== 'POST') {
        res.status(400).send({ message: 'Only POST requests allowed for this route' })
    } else {
        const { signes_id } = req.query
        const signes_array = signes_id.split(",").map(function(item) {
            return parseInt(item)
        })
        console.log(signes_array)
        const ret = await prisma.signe.findMany({
            where: {
                id: Number(signes_array),
            }
        })
        res.status(200).send(ret)
    }
}

This does not work as Number expects an int, not an array of int

How can I write the query such as it returns the needed array of objects ?
And how can I deal with id's that do not match ?

1 Answers1

88

You can use the in operator to query by multiple id inside findMany.

Example:

 const ret = await prisma.signe.findMany({
            where: {
                id: { in: [1, 2, 12] },
            }
        })

More details are available in the prisma client reference.

Tasin Ishmam
  • 5,670
  • 1
  • 23
  • 28
  • This will filter duplicate posts and bring them back. What if you want to bring them all? – dontknowhy Nov 19 '22 at 07:27
  • @nounlace just to clarify, are you asking what to do if you want duplicate records to be returned by `findMany` when you have an array of `id` fields with duplicate `id` values? – Tasin Ishmam Nov 19 '22 at 09:45
  • yup yup exactly – dontknowhy Nov 20 '22 at 02:34
  • 1
    @nounlace Hey, sorry for the delay. Unfortunately, it's not possible to do that with a single Prisma query at the moment. I would suggest fetching the entries _without_ duplicates and then organizing them _with_ duplicates inside your application code. If you make a separate question for this and link it, I'd be happy to provide a code snippet that shows how to accomplish this. – Tasin Ishmam Dec 01 '22 at 14:07