docs icon indicating copy to clipboard operation
docs copied to clipboard

Help article for "Querying models based on their relations existence" only describes list relationships

Open hiddenist opened this issue 3 years ago • 1 comments

https://www.prisma.io/docs/support/help-articles/finding-entities-based-on-relation

This help article only explains how to query existence on a list relationship, but not if the related model is singular.

Using the same example schema:

model User {
  id    Int    @id @default(autoincrement())
  name  String
  posts Post[]
}

model Post {
  id     Int   @id @default(autoincrement())
  user   User? @relation(fields: [userId], references: [id])
  userId Int?
}

How would one write a query on all posts that have a user? Or that don't have a user?

await prisma.post.findMany({
  where: { user: /* user exists? */ },
})
await prisma.post.findMany({
  where: { user: /* user does not exist? */ },
})

hiddenist avatar Jul 15 '21 20:07 hiddenist

Still wondering about this. Is this the correct syntax?

await prisma.post.findMany({
  where: {
    user: { isNot: null }
  },
})
await prisma.post.findMany({
  where: {
    user: { is: null }
  },
})

hiddenist avatar May 16 '22 18:05 hiddenist

Hey 👋

Apologies for the delayed response. You can filter for null if a relation is singular as follows:

await prisma.post.findMany({
  where: {
    author: null
  }
})

We'll add this to the docs soon. 🙂

ruheni avatar May 03 '23 13:05 ruheni