Prisma get all tree

Viewed 1626

I'm using Prisma new project. I've Category recursive relation :

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

This relation work nice, but for get all categories with all children (full tree, not only 1 level), i don't know if it's possible with Prisma ? It's generally called eager loading.

With this request, i get only first children, but i would like get very all tree, do you know if it's possible ?

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

Thank you !

2 Answers

In this case, you would need to explicitly specify how many levels you require in include as Prisma doesn't support fetching recursive relations.

Another option if you're using Postgres is to use a recursive CTE (via with).

Check the docs here. It shows how what you want to achieve is possible, but may become a little annoying for deep relations. Here is an example:

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