Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

create another support article #1175

Merged
merged 9 commits into from
Jan 15, 2021
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
---
title: 'Querying models based on their relations existence'
metaTitle: 'Querying models based on their relations existence'
metaDescription: 'Learn how you can query for entities where their relation exists or not'
---

## Problem

Common use cases when querying for relations from a database are:

- finding all the entities for table X where the relation Y doesn't exist
- finding all the entities for table X where the relation Y has at least one item

Taking a concrete example of users and posts as entities, this would translate to _"find the users that haven't created any posts"_ and _"find the users that have created at least one post"_.

Read below to learn how this can be achieved with Prisma.

## Solution

Consider this Prisma schema:

```prisma
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?
}
```

You can now query for the **users that do not have any posts** as follows:

```js
await prisma.user.findMany({
where: { posts: { none: {} } },
})
```

This query returns all the users that haven't created any posts yet.

In a similar way, you can query for **users that created at least one post** as follows:

```js
await prisma.user.findMany({
where: { posts: { some: {} } },
})
```

This query returns all the users that created at least one post.

This article showed how you can query for entities based on if the relation exists.