model Post { id Int@id@default(autoincrement()) title String // 外键:绑定用户id userId Int // 关联关系:多篇文章 对应 一个用户 userUser@relation(fields: [userId], references: [id]), onDelete:Cascade onUpdate: Cascade }
详细分析如下:
userId Int:
外键字段
用来记录:这篇文章是哪个用户写的
存的就是 User 表里的用户 id
user User:
前面 user:你自己取的关联字段名(随便起名)
后面 User:关联的另一张表模型名(User 用户表)
意思:这条数据,对应 一个 User 用户
fields: [userId]
fields = 当前 Post 表里的 userId
用我自己这个表里的 userId 去做关联匹配
references: [id]
references = 对面 User 表里的 id 主键
onDelete: Cascade:
级联删除,如果你把 User 用户删掉了
👉 这个用户下面所有关联的 Post 文章,自动全部跟着一起删掉
用文章表里的 userId,去匹配用户表里的 id 把两张表建立绑定关系, 代表:这篇文章属于这个用户。 fields 自己的外键 references 对方的主键
onDelete: Restrict(默认)
有文章存在 → 用户不让删,直接报错
onDelete: SetNull
删用户 → 文章保留,userId 变成 null
onUpdate: Cascade:
级联更新(表示更新主表的时候,从表也更新,非常的方便啊)
1 2 3 4
model User{ roles Role[] @relation("UserRoles") //这是多对多的关系,会自动创建关联的表UserRoles }