How to get counts on relations with Prisma client

On version 2.20 with Prisma, we have got a new feature that helps you get a number of counts on related fields. Let's use an example where we have a type Author with related field posts and comments as we can see below. 

This is imperative when we have a dashboard or using it on a dashboard where we can extract the number of posts or comments on an Author. 

And to get a sense of what this data might look like in the Prisma database, we have the author table having 3 posts and 1 comment as shown in the database. 

The database base often shows these counts but it wasn't easy getting these counts with the Prisma client. But with the new previewFeatures option we can now view the number of counts on our relation types.

Step A:

1.  Include the previewFeatures option in your Prisma client and set its value as "selectRelationCount" as shown below. The previewFeatures is the option that makes it possible to query the count on the relations on the Author.

2. Then run $ npx prisma generate to the latest Prisma client. After generating the client we will be able to immediately use the new client.

Step B: 

1. Let's use a findMany prisma function to find specific relations on the author.

2. With the include parameter, we navigate through the _count and select the relation we want to show by setting them to true.


Post a Comment

Post a Comment (0)

Previous Post Next Post