簡體   English   中英

Prisma :我怎樣才能讓所有孩子都處於某種狀態?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM