2
type Category {
  id: ID! @id
  name: String!
}

type SubCategoryLevel1 {
  id: ID! @id
  name: String!
  parentCategory: Category! @relation(link: INLINE)
}

type SubCategoryLevel2 {
  id: ID! @id
  name: String!
  parentCategory: SubCategoryLevel1! @relation(link: INLINE)
}

What if my Category levels are not decided, I'm using Prisma ORM and MongoDB.

Rohan Shukla
  • 533
  • 1
  • 4
  • 16

1 Answers1

8

Not sure I correctly understand your question. Could you go into a bit more detail what you are trying to do?

Are you trying to do arbitrarily deeply nested self-relations? Then you can do something like this:

type Category {
  id: ID! @id
  name: String!
  subCategory: Category @relation(name:"SubToParent"link: INLINE)
  parentCategory: Category @relation(name: "SubToParent")
}

Creating three levels would work with this query:

mutation createCategory {
  createCategory(
    data: {
      name: "firstLevel"
      subCategory: {
        create: {
          name: "secondLevel"
          subCategory: { create: { name: "thirdLevel" } }
        }
      }
    }
  ) {
    name
  }
}

And querying for categories would give you this response:

query allCategories {
  categories {
    name
    subCategory {
      name
    }
    parentCategory {
      name
    }
  }
}

{
  "data": {
    "categories": [
      {
        "name": "firstLevel",
        "subCategory": {
          "name": "secondLevel"
        },
        "parentCategory": null
      },
      {
        "name": "secondLevel",
        "subCategory": {
          "name": "thirdLevel"
        },
        "parentCategory": {
          "name": "firstLevel"
        }
      },
      {
        "name": "thirdLevel",
        "subCategory": null,
        "parentCategory": {
          "name": "secondLevel"
        }
      }
    ]
  }
}

I hope that helps, if not just explain your question in a bit more detail.

Matthias Oertel
  • 774
  • 3
  • 10
  • If the parentId is null then it is my Main Categories, other it is sub-category. I am unable to query Category where my parentId is null – Rohan Shukla Jan 09 '19 at 10:47
  • Does it throw an error or do you not know how to query for that? – Matthias Oertel Jan 09 '19 at 17:35
  • When I try to query I get all the result stored in categories, but I want the data of parentCategory which has null value, I think I'm missing something in query or apparently I'm not writing correct query. However I did try to search all over the internet. I tried to below query, though I know it is not right. `ctx.db.query.categories({ where: { id_not: parent.parentId } }, info)` – Rohan Shukla Jan 10 '19 at 05:26
  • I think `categories({ where: {parentCategory: null } }` should work If I understand you correctly. – Matthias Oertel Mar 07 '19 at 12:29