Get Posts With selected tags using Prisma

Viewed 39

How can I get posts that have selected tags (filter by tag id) ?

Here are the models I'm using :

model Post {
  id    Int        @id @default(autoincrement())
  title String
  tags  PostTags[]
}

model PostTags {
  id     Int   @id @default(autoincrement())
  post   Post? @relation(fields: [postId], references: [id])
  tag    Tag?  @relation(fields: [tagId], references: [id])
  postId Int?
  tagId  Int?
}

model Tag {
  id    Int        @id @default(autoincrement())
  name  String     @unique
  posts PostTags[]
}

I tried to filter posts using this query but I'm getting also posts that have zero tags :

const posts = await prisma.post.findMany({ 
  where: { tags: { every: { id: { in: tags_arrays_ids } } } } 
})
1 Answers

To filter posts and not include posts that have zero tags, use this query

const posts = await prisma.post.findMany({
    where: {
      tags: {
        some: {
          id: {
            in: tags_arrays_ids
          }
        }
      }
    }
  })

Notice how the only difference between your query and this one is the use of the some property. To learn more about it, check out the prisma docs.

Related