自关联
关系的目标可以是模型自身:树形结构用父节点加反向的子节点集合,社交关系在同一个模型上写多对多。
定义
树形结构使用可选的父节点字段与反向子节点集合;有向多对多关系使用持有方数组与反向数组。两种写法的目标都是当前模型。
示例
分类树:
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 在父分类删除时把子分类提升为根节点,但不检查环。
关注关系,两侧都在同一个模型上:
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
注意事项
- 自关联多对多的两个数组都是必需的。中间表按持有方数组命名,
User.following生成_User_following。 - 读取树就是普通的关系过滤,见关系过滤。