Prisma:如何让所有孩子都符合条件?

Mat*_*tte 2 typescript next.js prisma

我正在尝试在多对多表上使用 prisma (引用自身),这样的行将有子代和孙代

我可以毫无问题地获取所有行,但我正在努力了解如何以可读的 JSON 形式对数据进行排序,这将阻止在前端进行解析

预期输出如下:返回的 JSON 的根只会引用父母,父母将引用他们的孩子,孩子将引用他们自己的孩子

重要注意事项:我只能返回启用= true的元素

我使用的表称为先行词并遵循此 prisma 模式:

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
}
Run Code Online (Sandbox Code Playgroud)

到目前为止我已经得到了这个:

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)
}
Run Code Online (Sandbox Code Playgroud)

这对于父母来说非常有效,但我找不到如何对孩子施加条件(例如enabled = true),并且它根本不显示孙子

如何以不需要任何解析的方式返回数据?

Tas*_*mam 6

您可以在内部添加where条件include以及进行任意级别的嵌套。这就是您的用例的语法

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
            }
        },
    }
});
Run Code Online (Sandbox Code Playgroud)

更多信息请参阅Prisma 文档中的关系查询文章。