The simplest example I can give, is a User that can create multiple Posts. A one-to-many relationship where multiple posts can be tied to a single user.
But what if I want the User to only be able to have a max of 10 Posts? Ideally there’d be some kind of query I can run when creating a new Post, and if the limit has been reached, to reject creating that Post (or possibly replace a Post).
I’m kind of stumped on this. And I’m not sure if there is a way I can model this to create the desired outcome.
Otherwise, the only real solution I see is to fetch all Posts for a User, and count them before trying to create a new Post. But that would require two calls to the db instead of one which is the problem I am trying to avoid.
2
Answers
Have you considered a database trigger? Below example is taken from this StackExhange post:
Unfortunately triggers don’t seem to be supported in Prisma yet, so you will have to define it in SQL: https://github.com/prisma/prisma/discussions/2382
You can achieve it with interactive transaction, here’s my example code: