typescriptprismaprisma2

How do I filter if an optional relationship exists?


I have the following schema where Quiz is an optional relationship on User.

model User {
  email String @id @unique
  quiz  Quiz?
}

model Quiz {
  id        String @id @default(uuid())
  user      User   @relation(fields: [userEmail], references: [email], onDelete: Cascade)
  userEmail String
}

I want to find all users that do have a quiz relationship.

At first I naively tried the following:

const users = await p.user.findMany({
  where: { quiz: true },
})

Then I thought I found a solution in their docs.

const users = await p.user.findMany({
  where: { quiz: { some: {} } },
})

But this gives the error:

Type '{ some: {}; }' is not assignable to type '(Without<QuizRelationFilter, QuizWhereInput> & QuizWhereInput) | (Without<QuizWhereInput, QuizRelationFilter> & QuizRelationFilter) | null | undefined'.

Object literal may only specify known properties, and 'some' does not exist in type '(Without<QuizRelationFilter, QuizWhereInput> & QuizWhereInput) | (Without<QuizWhereInput, QuizRelationFilter> & QuizRelationFilter)'.

9 where: { quiz: { some: {} } },


Solution

  • The solution you found in the docs works for one-to-many relations. One-to-one relations can be filtered like this:

    const users = await p.user.findMany({
      where: { quiz: { isNot: null } },
    });