Home > Back-end >  Prisma : how can I find all elements that match an id list?
Prisma : how can I find all elements that match an id list?

Time:11-06

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 ?

CodePudding user response:

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.

  • Related