我的模式中有以下模型:
model Collection {
id String @id @default(cuid())
title String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
parent Collection? @relation("CollectionChildren", fields: [parentId], references: [id])
parentId String?
children Collection[] @relation("CollectionChildren")
}
我得到的是集合的自关系。他们可以有无限的等级。现在,我想查询和排序并列出它们,以便最终结果如下所示:
- 收集1
- 收集2
- Collection 2 Child 1
- Collection 2 Child 2
- Collection 2 Child 3
- 收集3
- Collection 3 Child 1
- Collection 3 Child 1子Child 1
- Collection 3 Child 2
- Collection 3 Child 3
- Collection 3 Child 1
- 收集4
问题是,我不知道如何查询然后,使他们按标题排序,同时也按父组。
这在Prisma/Postgres中是可能的吗?
如果不知道子关卡的深度,就很难得到所有的子关卡(就像你提到的,可能有无限的关卡)。
Prisma有一个支持递归关系的特性请求#3725
作为一种解决方法,您需要使用Raw Query。
SQL查询可以看起来像这样:
WITH RECURSIVE collection_tree AS (
SELECT id, title, parentId
FROM Collection
WHERE parentId IS NULL
UNION ALL
SELECT c.id, c.title, c.parentId
FROM Collection c
JOIN collection_tree ct ON ct.id = c.parentId
)
SELECT *
FROM collection_tree
ORDER BY title;
该查询使用递归CTE首先选择顶级集合(其中parentId
为null
),然后通过将collection_tree
CTE与parentId
上的Collection表连接来选择这些集合的所有子集合。结果是所有集合及其子集合的扁平列表,按title字段排序。