Create a Relation Between Two Tables in the Prisma Schema

Ryan Chenkie
InstructorRyan Chenkie

Share this video with your friends

Send Tweet
Published 3 months ago
Updated a month ago

Prisma Schema Language is used to model our database tables and establish relations between them. Prisma offers autocompletion to register the relations. In this lesson, we create a new model for a second database table and see how to relate our two tables together.

Instructor: [0:00] Prisma makes it very simple to relate one table to another. In a relational database, like we're using here with SQLite, it is very often the case that we'll want to have relations between different tables. Create another table that can be used alongside the main product table for reviews.

[0:17] Model review will create a new table. Use the same ID structure that is contained within product to provide an ID to the review table. Then provide the other properties that are relevant to a review, for example, text, which should be a string, and rating, which should be an integer.

[0:33] At this point, these two tables are not related together. They are standing on their own. To relate the two tables together, some information is required on each of the models. Add a new property to the product table called reviews, and for its type, say that it should be of type review, which points to the review model, and that this should be a one-to-many relation. A single product has many reviews. The many is denoted by the array-like syntax here.

[1:02] Save schema.prisma, and you'll see that there is a lot of information auto-completed. This auto-completion happens through the Prisma VSCode extension. In the review model, this new property called product is pointing up to the product model. Prisma automatically takes the casing from the model name, and most people come over and make this lowercase to abide by the rest of their property names.

[1:24] Prisma automatically made the relation to product optional for a review, but the business logic for this application says that reviews must be related to a product. To fix that, erase the question marks.

[1:36] The key name product here points to a virtual field called product, which is the Prisma model that is created above, and product ID is a string type that will be kept in the database table for review, which will point to product. Save the schema file and migrate the database, npx prisma migrate dev.

[2:00] The migration name can be Add Review. Check out the new table over in Prisma Studio. Open up a new table with the plus icon and check out review under All Models.