mongodbgraphqlprismaprisma-graphqlplumatic-schema

How to create Categories and its SubCategory in Prisma ORM using MongoDB


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.


Solution

  • 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.