Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
11 replies
Chill Guy

How do I query self-relations?

I guess my schema must be wrong. But I think I've followed the Prisma docs carefully. I currently have the schema beneath. I am trying to query a user by its id, and include the following and followedBy. But it aint working. I am just receiving the 500 status (from the catch block).

The schema

model User {
  id            String        @id @default(cuid())
  name          String?
  email         String?       @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  following     UserFollows[] @relation("follower")
  followedBy    UserFollows[] @relation("following")
}

model UserFollows {
  follower    User   @relation("follower", fields: [followerId], references: [id])
  followerId  String
  following   User   @relation("following", fields: [followingId], references: [id])
  followingId String

  @@id([followerId, followingId])
  @@index([followerId])
  @@index([followingId])
}


The query

try {
    const data = await prisma.user.findFirst({
      where: {
        id: id as string
      },
      include: {
        following: true,
      }
    });
  
    return new Response(JSON.stringify(data));
  } catch (error) {
    console.error(error);
    return new Response("Internal Server Error", { status: 500 });
  }
Was this page helpful?