Get custom attribute depend on pivot table in nest js with prisma ORM

Viewed 113

What is the efficient way to map Prisma query results depending on the logged-on user and pivot table?

Here is my schema

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  email     String  @unique
  password  String
  firstName String
  lastName  String?

  favouriteMovies FavouriteMovie[]

  @@map("users")
}

model Movie {
  id              Int              @id @default(autoincrement())
  createdAt       DateTime         @default(now())
  updatedAt       DateTime         @updatedAt
  title           String
  year            Int
  rating          Float
  category        String
  posterUrl       String
  favouriteMovies FavouriteMovie[]

  @@map("movies")
}

model FavouriteMovie {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt


  user    User  @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId  Int
  movie   Movie @relation(fields: [movieId], references: [id], onDelete: Cascade)
  movieId Int
  @@map("favourite_movies")
}

Which is the best way to retrieve isFavourite attribute with the Movie query result?

1 Answers

Here's the query which would return the movie details of the logged-in user.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  // Creating User
  const user = await prisma.user.create({
    data: {
      email: 'sundarani@prisma.io',
      firstName: 'Nurul',
      lastName: 'Sundarani',
      password: 'test',
    },
  });

  // Creating Movie
  const movie = await prisma.movie.create({
    data: {
      title: 'The Matrix',
      category: 'Action',
      posterUrl: 'https://i.imgur.com/dZQMx5q.jpg',
      rating: 5,
      year: 1999,
    },
  });

  // Adding movie to user
  const favouriteMovie = await prisma.favouriteMovie.create({
    data: {
      movieId: 1,
      userId: 1,
    },
  });

  // Getting Movie details of favourite movie of user
  const getMovieDetailsFromUserId = await prisma.favouriteMovie.findMany({
    where: {
      userId: 1, // Logged In User
    },
    include: {
      movie: true,
    },
  });

  console.log(getMovieDetailsFromUserId);
}

main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Response:

[
  {
    id: 1,
    createdAt: 2022-06-14T11:31:49.415Z,
    updatedAt: 2022-06-14T11:31:49.417Z,
    userId: 1,
    movieId: 1,
    movie: {
      id: 1,
      createdAt: 2022-06-14T11:30:10.747Z,
      updatedAt: 2022-06-14T11:30:10.747Z,
      title: 'The Matrix',
      year: 1999,
      rating: 5,
      category: 'Action',
      posterUrl: 'https://i.imgur.com/dZQMx5q.jpg'
    }
  }
]

Reference: Include.

Related