Self-Relations
A relation can target its own model: trees use a parent pointer with an inverse collection of children, social graphs use a many-to-many relation on the same model.
Definition
Use a single optional parent field with an inverse collection for a tree, or an owning array with an inverse array for a directed many-to-many graph. In either case, the relation target is the current model.
Example
A category tree:
ts
model Category {
id: int @id @auto
name: string(64)
parent?: Category @relation(onDelete: SetNull)
children: Category[] @via(parent)
}1
2
3
4
5
6
2
3
4
5
6
onDelete: SetNull promotes children to root level when their parent is deleted; cycles are not detected.
A follower graph, where both sides live on the same model:
ts
model User {
id: int @id @auto
email: string @unique
following: User[]
followers: User[] @via(following)
}1
2
3
4
5
6
2
3
4
5
6
Notes
- Both arrays in a self-referencing many-to-many are required. The join table is named after the owning array, so
User.followingproduces_User_following. - Reading a tree is an ordinary relation filter; see Relation Filters.
Next Steps
- Multiple Relations: two different models sharing several relations
- Referential Actions: what happens when a row is deleted