model Category { id Int @id @default(autoincrement()) name String parentId Int? parent Category? @relation("CategoryHierarchy", fields:[parentId], references:[id]) children Category[] @relation("CategoryHierarchy")}
Required
Detail
Relation name
Mandatory for self-relations
2. Creating One-to-One Self-Relation
model User { id Int @id @default(autoincrement()) mentorId Int? @unique mentor User? @relation("Mentorship", fields:[mentorId], references:[id]) mentee User? @relation("Mentorship")}
Key
Detail
Uniqueness
@unique on FK forces 1:1
3. Creating One-to-Many Self-Relation
Example
Notes
Tree / hierarchy
Category → children
Comments tree
Comment → replies
4. Creating Many-to-Many Self-Relation
model User { id Int @id @default(autoincrement()) followers User[] @relation("Followers") following User[] @relation("Followers")}
const tree = await prisma.$queryRaw` WITH RECURSIVE t AS ( SELECT id, name, "parentId" FROM "Category" WHERE id = ${rootId} UNION ALL SELECT c.id, c.name, c."parentId" FROM "Category" c JOIN t ON c."parentId" = t.id ) SELECT * FROM t`;