【问题标题】:Prisma following/follower relationship schemaPrisma 追随者/追随者关系模式
【发布时间】:2021-10-09 23:56:08
【问题描述】:

我有一个用户模型,我想添加追随者/追随者系统,为此我认为我需要创建一个看起来像这样的单独表

id | user_id | follower_id
1  | 20      | 45
2  | 20      | 53
3  | 32      | 20

但我不知道如何为此创建架构,我所做的是:

model User {
  id         Int         @id @default(autoincrement())
  username   String
  Follows    Follows[]
}

model Follows {
  id           Int      @id @default(autoincrement())
  following_id Int?
  follower_id  Int?
  user_Following    User     @relation(fields: [following_id], references: [id])
  user_Follower     User     @relation(fields: [follower_id], references: [id])
}

但这当然不起作用,并且给我一个错误

【问题讨论】:

  • 错误是什么?

标签: javascript node.js postgresql database-design prisma


【解决方案1】:

这是我建议的模式建模方式。

model User {
  id        String  @id @default(autoincrement())
  username  String
  followers Follows[] @relation("follower")
  following Follows[] @relation("following")
}

model Follows {
  follower    User @relation("follower", fields: [followerId], references: [id])
  followerId  String
  following   User @relation("following", fields: [followingId], references: [id])
  followingId String

  @@id([followerId, followingId])
}

变化

  1. 用户表有两个关系字段而不是一个。
  2. followerIdfollowingId 是强制性的。当其中任何一个都不存在时,拥有Follows 关系表真的没有意义。 (如果没有一位用户关注和一位用户关注,您就无法建立关注关系)。
  3. @@id([followerId, followingId]) 代表Follows 表中的主键。单独的 id 字段是多余的。
  4. 将字段名称更改为 camelCase,这是 Prisma 中推荐的约定。

4 当然是可选的,但我还是建议遵循它。

您可以在 Prisma 文档中self-reation article 的多对多小节中找到更多详细信息。

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2017-12-08
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2021-02-18
    相关资源
    最近更新 更多