【问题标题】:Prisma get all tree棱镜得到所有的树
【发布时间】:2021-06-15 00:38:15
【问题描述】:

我正在使用 Prisma 新项目。我有类别递归关系:

model Category {
  id          Int        @id @default(autoincrement())
  name        String
  children    Category[] @relation("CategoryToCategory")
  parentId    Int?
  parent      Category? @relation(fields: [parentId], references: [id])
}

这种关系很好用,但是为了获得所有子类的所有类别(完整的树,不仅仅是 1 级),我不知道 Prisma 是否可行?通常称为急切加载

有了这个请求,我只得到第一个孩子,但我想得到所有的树,你知道这是否可能吗?

const allCategories = await db.category.findMany({
    include: {
      parent: true, // return only first level
      children: true, // return only first level
    },
  })

谢谢!

【问题讨论】:

    标签: mysql node.js hierarchical-data prisma


    【解决方案1】:

    在这种情况下,您需要在 include 中明确指定需要多少级别,因为 Prisma 不支持 fetching recursive relations

    如果您使用 Postgres,另一种选择是使用递归 CTE(通过 with)。

    【讨论】:

      【解决方案2】:

      查看文档here。它显示了您想要实现的目标是如何可能的,但对于深层关系可能会变得有点烦人。这是一个例子:

      const allCategories = await db.category.findMany({
        include: {
          parent: true,
          children: {
            include: {
              category: true
            }
          }
        }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-08
        • 2019-09-22
        • 2022-07-13
        • 2020-07-24
        • 2020-05-21
        • 2022-10-19
        • 2022-01-22
        相关资源
        最近更新 更多