Use Prisma Client to Connect Related Tables when Creating New Data

Ryan Chenkie
InstructorRyan Chenkie
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

Prisma Client has a specific API for relating data from one table to another when creating new records. In this lesson, we use the connect operator to establish a link between two tables as new records are created.

Ryan Chenkie: [0:00] The relation between product and review is a required relation. A review must be related to a product. While a product may have no reviews, it might just be an empty array, there is this explicit relationship between product and review.

[0:16] When we create new reviews in the database, we need to provide information about which product it is related to. Create a new endpoint to handle new reviews. Copy the post endpoint that is already in place for products. Call it "/reviews".

[0:32] This new endpoint will have a const of review for a new review. Instead of going to prisma.product, go to prisma.review. Prisma's type safety is helping us already by saying that what we have supplied for data is invalid. Instead, we have to supply the properties that are expected. We need text that will come from body.txt and we need rating.

[0:56] The data key here is still invalid, and that's because we haven't supplied the product id to connect to, to relate the review to a given product. To establish this connection, we say that we want to connect to a given product. Product points to an object, on which we supply the connect keyword, and we connect by the product id. This will come in on body.productId.

[1:24] At this point, the call to create is sound, so we should be able to go to our res client and create a new review. Save the endpoint and before going to the res client, go to Prisma Studio and look for a product id that we want to supply the review to. Copy over that id so that we can use it in our res client.

[1:42] In the res client, make a call to reviews. It's a POST call. The JSON content should take the shape of what we are expecting in our endpoint. We'll need a text key, we'll need a rating, and we'll need product id.

[2:04] Click Send to make the call. We can now verify in Prisma Studio, and in the browser that the review was put into the database. In the call to products, we can see that we have the review coming through.