next.js – GraphQL query returns an empty array on many-to-many relation – Prisma-Pothos
I’ve been struggling for some days now and feel dumb. I’m new to GraphQL and Prisma.
I’m creating a simple CRUD app with Next.js, GraphQL-Yoga, Prisma, Pothos, Apollo-Client and auth0. I use supabase for a PostgreSQL database. I want to query the posts and the corresponding user for each post. So I can map over it in react and display for example the role and the email of each user next to their post. I made a many-to-many relationship in the schema.prisma.
I tried using a one-to-many relation but I could only get, for example, the id, not the id and the email simultaneously.
GraphQL-Playground query:
query MyQuery {
posts {
title
id
user {
email
id
}
}
}
The user remains empty. Output:
{
"data": {
"posts": [
{
"title": "Lettuce",
"id": "1",
"user": []
},
{
"title": "Banana",
"id": "2",
"user": []
},
{
"title": "Carrot",
"id": "3",
"user": []
}
]
}
}
// /prisma/schema.prisma:
model User {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String? @unique
image String?
role Role @default(USER)
Posts Post[]
}
model Post {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
description String
category String
User User[]
}
// /graphQL/types/Post.ts
import { builder } from "../builder";
builder.prismaObject("Post", {
fields: (t) => ({
id: t.exposeID("id"),
title: t.exposeString("title"),
description: t.exposeString("description"),
category: t.exposeString("category"),
user: t.relation("User"),
}),
});
builder.queryField("posts", (t) =>
t.prismaField({
type: ["Post"],
resolve: (query, _parent, _args, _ctx, _info) =>
prisma.post.findMany({
...query,
}),
})
);
It seems like this is what I need but when I integrate the <builder.queryType> portion I get an error saying:
PothosSchemaError: Duplicate typename: Another type with name Query already exists.
I tried some other things and got nothing. It seems like REST is so much easier.
Read more here: Source link