如何优化Prisma嵌套查询,仅返回顶级产品分类树形结构?
解决Prisma分类树形结构查询问题
问题场景
现有如下产品分类的Prisma模型:
model ProductCategory { categoryId Int @id @default(autoincrement()) categoryName String @db.VarChar(50) slug String @db.VarChar(50) parent ProductCategory? @relation("Subcategories", fields: [parentId], references: [categoryId]) parentId Int? subcategories ProductCategory[] @relation("Subcategories") }
当前使用以下代码查询分类:
const data = await prisma.productCategory.findMany({ select: { categoryId: true, categoryName: true, slug: true, subcategories: { select: { categoryId: true, categoryName: true, slug: true, subcategories: { select: { categoryId: true, categoryName: true, slug: true, }, }, }, }, } });
查询结果会返回所有层级的分类(顶级分类、子分类、孙分类均单独作为根条目出现),但需求是仅返回顶级分类及其嵌套的子分类、孙分类的树形结构,期望结果示例:
{ "categoryId": 10, "categoryName": "Main Category", "slug": "main-category", "subcategories": [ { "categoryId": 11, "categoryName": "Sub Category", "slug": "sub-category", "subcategories": [ { "categoryId": 12, "categoryName": "Sub Category 1", "slug": "sub-category-1" }, { "categoryId": 13, "categoryName": "Sub Category 2", "slug": "sub-category-2" } ] } ] }
解决方案
核心思路是仅筛选查询顶级分类(即parentId为null的分类),同时保留原有的嵌套select配置来获取子层级数据,这样返回的结果就只会是顶级分类包含嵌套子分类的树形结构,不会出现下级分类单独成根条目的情况。
修改后的查询代码:
const data = await prisma.productCategory.findMany({ // 筛选出没有父分类的顶级条目 where: { parentId: null }, select: { categoryId: true, categoryName: true, slug: true, subcategories: { select: { categoryId: true, categoryName: true, slug: true, subcategories: { select: { categoryId: true, categoryName: true, slug: true, }, }, }, }, } });
补充说明
- 若你的分类层级超过三级,可以继续在
subcategories中嵌套对应的select结构,来获取更深层级的分类数据 - 添加
where条件后,Prisma只会查询顶级分类,再通过关联关系自动加载其下属的所有子分类层级,完美匹配需求的树形结构
内容的提问来源于stack exchange,提问作者Irfan Arif
相关产品推荐
相关产品推荐

