简体   繁体   中英

How to made a relation to user model using Prisma?

I'm trying to query comments and the user who made the comments. I'm using Prisma to create the schema and Planetscale as a database.

Below you find part of my schema


model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  Comment       Comment[]
}

model Comment {
  id          String   @id @default(cuid())
  text        String
  contentId   String
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
  commenterId String?
  commenter   User?    @relation(fields: [commenterId], references: [id])
}

This is my API route:

import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../../lib/prisma";

export default async function handle(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "GET") {
    return res.status(405).json({ msg: "Method not allowed" });
  }

  try {
    const comments = await prisma.comment.findMany();
    return res.status(200).json(comments);
  } catch (err) {
    console.error(err);
    res.status(500).json({ msg: "Something went wrong." });
  }
  res.end();
}

The end goals is to query the comments and get an object with the commenter, so I can display name and image.

How should my @relation in the model Comment look like to make it possible to include the commenter in the query?

You need to tell prisma if you want to include a related model like this:

await prisma.comment.findmany({
  include: {
    commenter: true,
  },
})

https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM