Sebastian Stuecker
Sebastian Stuecker

Reputation: 113

Is there a way in prisma to filter based on a "Has Childs?" Condition?

I am using Prisma2 with Typescript and node.js and I am using the approach with an introspected mysql DB with foreign key relationships. Previously I used .net core Entityframework and I am trying to find out if and how certain functionality is possible to do in TS/Prisma.

I have 2 tables connected with a one to many relationship like Authors Posts 1 Author can have many posts, some authors have no posts.

I want to query only those authors who have at least one post. more general i might want to filter only those authors which have more then 2 or exactly 2 posts, etc, or to dive in more deeply, only those authors who have at least 1 post that also have to have at least one comment.

I tried all kinds of things e.g.

const result = await prisma.authors.findMany({
   where:{ 
      posts:{
         none:{
            id: undefined
         }
      }
   }
 });

but thats not it. Is there simple way to achieve this?

Upvotes: 0

Views: 1074

Answers (1)

Ryan
Ryan

Reputation: 6327

For users that have one or more posts (at least one post), this should work:

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

Upvotes: 1

Related Questions