如何使用 MongoDB 在 Prisma ORM 中创建类别及其子类别

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)
}

如果我的 Category 级别未确定怎么办,我正在使用 Prisma ORM 和 MongoDB。

不确定我是否正确理解了你的问题。您能否更详细地说明您要做什么?

您是否正在尝试进行任意深度嵌套的自我关系?然后你可以这样做:

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

创建三个级别将适用于此查询:

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

并且查询类别会给你这个响应:

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"
        }
      }
    ]
  }
}

希望对您有所帮助,如果不能更详细地解释您的问题的话。