Search code examples
javascriptnode.jspostgresqldatabase-designprisma

Prisma following/follower relationship schema


I have a user model, and i want to add following/followers system, and for that i think i need to create a separate table that looks like this

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

but i have no idea how to create the schema for that, what I've done is this:

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

but that of course doesn't work and is giving me an error


Solution

  • Here's the way I'd suggest modeling your schema.

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

    Changes

    1. User table has two relation fields instead of one.
    2. followerId and followingId are made mandatory. It doesn't really make sense to have a Follows relation table when either of those are absent. (You can't have a following relationship without one user following and one user to follow).
    3. @@id([followerId, followingId]) represents the primary key in Follows table. A separate id field is redundant.
    4. Changed field names to camelCase, which is the recommended convention in Prisma.

    4 is optional ofcourse, but I'd suggest following it none the less.

    You can find more details about this in the many-to-many subsection of the self-reation article in the Prisma doc.