pasek
pasek

Reputation: 419

How to get sql result with only rows that has a connected relations row

I am trying to query a database using the Prism Client and want to get back only the rows that has a foreign key in a joined table.

For example, get all users who have also created a post. I need a kind of "INNER JOIN".

I have tried something like:

return this.prisma.user.findMany({
    where: {
        Post: {
            some: {
                id: {
                    not: 0,
                }
            }
        }
    }
});

But the result is not the correct one. I'm not sure how to use "none, some or every"

Upvotes: 2

Views: 564

Answers (1)

Ryan
Ryan

Reputation: 6347

Suppose I have a schema like this:

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

model Post {
  id        Int      @default(autoincrement()) @id
  title     String
  user      User?    @relation(fields: [userId], references: [id])
  userId    Int?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

I get the users without any posts via the following query:

  const usersWithoutPosts = await prisma.user.findMany({
    where: {
      posts: {
        none: {
          id: undefined,
        },
      },
    },
  })

Could you try this way and check?

Upvotes: 3

Related Questions