[英]Prisma : how can I find all elements that match an id list?
I am using Prisma with NextJs.我正在将 Prisma 与 NextJs 一起使用。
In my API, I send to the back end a list of numbers that correspond to id's of objects in my database.在我的 API 中,我向后端发送了一个数字列表,这些数字与我的数据库中对象的 ID 相对应。
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例如,如果我收到列表
[1, 2, 12]
,我想返回 ID 为 1、2 或 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这不起作用,因为
Number
需要一个 int,而不是一个 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 ?我该如何处理不匹配的 ID?
You can use the in
operator to query by multiple id
inside findMany
.您可以使用
in
运算符在findMany
通过多个id
进行查询。
Example:例子:
const ret = await prisma.signe.findMany({
where: {
id: { in: [1, 2, 12] },
}
})
More details are available in the prisma client reference .在prisma 客户端参考中提供了更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.