簡體   English   中英

Prisma 關注/關注者關系模式

[英]Prisma following/follower relationship schema

我有一個用戶 model,我想添加關注/關注者系統,為此我想我需要創建一個單獨的表,如下所示

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])
}

但這當然不起作用並且給我一個錯誤

這是我建議對您的模式進行建模的方式。

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

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 文檔中的自我反應文章的多對多小節中找到有關此的更多詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM