hollandThomas
hollandThomas

Reputation: 79

Find record with an empty relation

Say I have this prisma schema with an implicit m:n-relation of Post and Tag

model Post {
  id   String @id
  tags Tag[]
}

model Tag {
  id    Int    @id @default(autoincrement())
  posts Post[]
}

How do I find the first Post that has no associated Tags?

prisma.post.findFirst({
  where: {
    tags: {
      // are nonexistent (something like count === 0?)
    },
  },
}),

Thanks for the help :)

Upvotes: 1

Views: 1179

Answers (2)

Danila
Danila

Reputation: 18506

You can probably use orderBy by count of tags in ascending order and get the first one? Like that:

prisma.post.findFirst({
  orderBy: { tags: { _count: 'asc' } },
});

Upvotes: 2

Axi Gerrika
Axi Gerrika

Reputation: 13

Searching on the internet I've found a link where the official documentation gives information on how to manage lists --> here

There it gives this example:

const posts = await prisma.post.findMany({
  where: {
    tags: {
      isEmpty: true,
    },
  },
})

Try adapting that to your own situation.

Upvotes: 0

Related Questions