Use Prisma Client to Query for Related Data

Ryan Chenkie
InstructorRyan Chenkie

Share this video with your friends

Send Tweet
Published 3 months ago
Updated a month ago

When two tables are related to one another, we can use Prisma Client to query for data through those relations. In this lesson, we see how to use Prisma Client to tie together data from two separate tables and pull it out in a nested fashion.

Ryan Chenkie: [0:00] Prisma Studio is aware of the relations between different tables. This makes it easy to manage data. If we add a record for a new review and give it a rating, we can then choose which product we want to assign this review to. Let's say that it should go to the first one, which is shoes.

[0:18] We can save this record, and we now have one review with a relation to a product. If we check out that product, we can see the review that is related. Prisma Client allows us to easily pull out this relation information when we make queries.

[0:33] In the call to the products endpoint to get all the products, add some information to tell Prisma Client that we want to get the review as well. In the findMany call, add an object with the include keyword and say that we want to include reviews true. Save the endpoint and check it out in the browser.

[0:54] Reviews shows up as an array because it is a one-to-many relationship between product and review. For cases where there are no reviews, the array is just empty.