【问题标题】:Prisma : how can I get all children on a condition?Prisma:我怎样才能让所有孩子都处于某种状态?
【发布时间】:2021-12-17 04:58:59
【问题描述】:

我正在尝试在多对多表(引用自身)上使用 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 )并且它根本不显示孙子

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

【问题讨论】:

    标签: typescript next.js prisma


    【解决方案1】:

    您可以在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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      相关资源
      最近更新 更多