NickP
NickP

Reputation: 1414

Get all related models for Prisma many-to-many relation

I have the following Prisma schema:

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


model Event {
  id               String             @id @default(cuid())
  title            String
  description      String
  code             String
  num_tasks        Int
  num_beacons      Int
  createdAt        DateTime           @default(now())
  updatedAt        DateTime           @updatedAt
  owner            User               @relation(fields: [ownerId], references: [id])
  ownerId          String
  eventParticiants EventParticiants[]
  tasks            Tasks[]
  beacons          Beacons[]
}

model EventParticiants {
  event   Event  @relation(fields: [eventId], references: [id])
  eventId String
  user    User   @relation(fields: [userId], references: [id])
  userId  String

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@id([eventId, userId])
}

Each user can join multiple events and each event can be joined by multiple users. This is mediated by a middle table.

I would like to return all the events for a user but this does not seem to be working:

  const events = await prisma.user.findMany({
    where: { owner: { email: session.user.email } },
    select: {
      eventParticiants: {
      }
    },
    orderBy: { createdAt: "desc" },
  });

Upvotes: 0

Views: 496

Answers (1)

some-user
some-user

Reputation: 4894

You need to add another level of select or include to go from eventParticipants to events:

const events = await prisma.user.findMany({
  where: { owner: { email: session.user.email } },
  select: {
    eventParticiants: {
      include: {
        event: true
      }
    }
  },
  orderBy: { createdAt: "desc" },
});

Upvotes: 1

Related Questions