Nest.js + Prisma relationship constantly returning null

Nest.js + Prisma relationship constantly returning null


0

I’m using Nest.js + GraphQl + Prisma, and trying to create 3 tables: User, Post, and Viewers
When getting 1 post I need to add the user as viewer. Successfully saving it to the db but when returning the relationship, viewers is constantly null

Here’s my prisma schema:

model User {
  id            Int       @id @default(autoincrement())
  name          String
  email         String    @unique
  password      String
  role          UserRole  @default(user)
  refresh_token String?
  posts         Post[]
  viewedPosts   Viewers[]
}

model Post {
  id        Int       @id @default(autoincrement())
  title     String
  content   String
  author    User      @relation(fields: [author_id], references: [id])
  author_id Int
  viewers   Viewers[]
}

model Viewers {
  id     Int  @id @default(autoincrement())

  user   User @relation(fields: [userId], references: [id])
  userId Int

  post   Post @relation(fields: [postId], references: [id])
  postId Int

  @@unique([userId, postId])
}

here’s my findOne method in post service:

async findOne(id: number, viewer_id: number) {
    const foundViewer = await this.prismaService.viewers.findFirst({
      where: {
        postId: id,
        userId: viewer_id,
      },
      include: {
        user: true,
        },
    });
  
    if (foundViewer == null) {
      await this.prismaService.viewers.create({
        data: {
          userId: viewer_id,
          postId: id,
        },
      });
    }
  
    return this.prismaService.post.findFirst({
      where: {
        id,
      },
      include: {
        author: true,
        viewers: { // -> this is constantly returning null
          include: {
            user: true,
          },
        },
      },
    });
  }

and here’s how my GraphQl query looks like:

mutation getOnePost($id: Int!) {
  getOnePost(id: $id) {
    id
    title 
    content 
    author {
      id
      email
    }
    viewers {
      email
    }
  }
}

Share
Improve this question

0


Load 5 more related questions


Show fewer related questions

0

Reset to default



Browse other questions tagged

or ask your own question.

Leave a Reply

Your email address will not be published. Required fields are marked *