[英]Prisma : how can I get all children on a condition?
我正在尝试在多对多表(引用自身)上使用prisma,这样的行将有子级和大子级
我可以毫无问题地获取所有行,但我正在努力了解如何在可读的 JSON 中对数据进行排序,这会阻止前端解析
预期输出如下:返回的 JSON 的根将只引用父级,父级将引用他们的孩子,而孩子们将引用他们自己的孩子
需要注意的重要事项:我只能返回 enabled = true 的元素
我使用的表称为前因,并遵循以下棱镜模式:
model antecedant {
id Int @id @default(autoincrement())
name String
children antecedant[] @relation("antecedant_children")
parent antecedant? @relation("antecedant_children", fields: [parent_id], references: [id])
parent_id Int?
enabled Boolean @default(true)
creation_date DateTime @default(now())
update_date DateTime @updatedAt
}
到目前为止,我已经得到了这个:
import { PrismaClient, Prisma } from '@prisma/client'
const prisma = new PrismaClient()
export default async function handler(req, res) {
const ret = await prisma.antecedant.findMany({
where: {
enabled: true,
parent_id: null
},
include: {
children: true,
}
});
res.status(200).json(ret)
}
这对父母来说非常有效,但我找不到如何对孩子施加条件(例如 enabled = true )并且它根本不显示孙子
如何以不需要任何解析的方式返回数据?
您可以在include
添加where
条件以及进行任意级别的嵌套。 这就是您的用例的语法
let ret = await prisma.antecedant.findMany({
where: {
enabled: true,
parent_id: null
},
include: {
children: {
where: {
enabled: true,
},
include: {
children: true // grandchildren
// you can pass an object and impose conditions like where: { enabled: true } here as well
}
},
}
});
Prisma 文档中的关系查询文章中提供了更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.