gpt4 book ai didi

typescript - 棱镜 : how can I get all children on a condition?

转载 作者:行者123 更新时间:2023-12-02 18:28:13 25 4
gpt4 key购买 nike

我正在尝试在多对多表(引用自身)上使用 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)
}

这对 parent 来说非常有效,但我找不到如何对 child 施加条件(例如 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
}
},
}
});

有关更多信息,请参阅 relation queries article在 Prisma 文档中。

关于typescript - 棱镜 : how can I get all children on a condition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69814261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com