Prisma:我怎样才能获得所有 children 的条件?

Prisma : how can I get all children on a condition?

我正在尝试在多对多 table(引用自身)上使用 prisma 这样的行将有 children 和 grand children

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

预期输出如下:returned JSON 的根将仅引用 parents,parents 将引用其 children 而 children 将引用他们自己的 children

需要注意的重要事项:我只能 return enabled = true 的元素

我使用的 table 称为先行词并遵循此棱镜模式:

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)
}

这对 parents 非常有效,但我找不到如何在 children 上施加条件(例如 enabled = true )并且它不显示盛大的 children完全

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

您可以在 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 文档的 relation queries article