Modeling a rating system in Prisma

Viewed 235

I want to include a rating system (like YouTube has it) in my project (using Next.js). How should I model the rating in Prisma-language?

I know this is a short question. It deserves a short answer.

Thanks, guys!

1 Answers

Here's a Prisma schema that would allow you to record ratings for movies and the associated user who rated the move:

model User {
  id           Int       @id @default(autoincrement())
  email        String    @unique
  city         String
  name         String?
  ratingsGiven Ratings[]
}

model Movie {
  id      Int       @id @default(autoincrement())
  name    String    @unique
  year    DateTime
  Ratings Ratings[]
}

model Ratings {
  id      Int     @id @default(autoincrement())
  rating  Decimal
  movie   Movie   @relation(fields: [movieId], references: [id])
  movieId Int
  user    User    @relation(fields: [userId], references: [id])
  userId  Int
}

This uses a decimal to represent the rating. If you wanted to do something simpler, you could just have thumbs up and down fields on the Movie model which you increment on user clicks:

model Movie {
  id      Int       @id @default(autoincrement())
  name    String    @unique
  year    DateTime
  thumbsUp Int
  thumbsDown Int
}

With this simpler model, you could use the atomic number operations to increment and decrement:

const updatedMovie = await prisma.movie.update({
  where: { id: 10 }
  data: {
    thumbsUp: {
      increment: 1,
    },
  },
})
Related