簡體   English   中英

棱鏡得到所有的樹

[英]Prisma get all tree

我正在使用 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
    },
  })

謝謝 !

在這種情況下,您需要明確指定include所需的級別,因為 Prisma 不支持獲取遞歸關系

如果您使用 Postgres,另一種選擇是使用遞歸 CTE(通過with )。

此處查看文檔。 它顯示了您想要實現的目標是如何可能的,但對於深層關系可能會變得有點煩人。 這是一個例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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