Consider this scenario: You are building a blog application and want to add a feature that allows the user to see a list of articles written by a specific author. How can you implement this feature?
To solve this problem, we must discuss relations. For a real-life application, the tables in your database are usually interconnected, meaning they have some kind of relationship with each other. For instance, in our blog application, each user could have multiple posts, and each post could have multiple tags.
In this lesson, we are going to discuss how to create such relations in an Express.js application using Prisma.js.
The one-to-one relation
There are three most fundamental types of relations.
First of all, there is the one-to-one relation, meaning each record in table A owns just one record in table B, and vice versa. For example, each user could have one phone, and each phone only belongs to one user.
To achieve such a relation, your User
table should have a phoneId
column, storing the id
of the phone that each user owns. Of course, you could choose a different name for that column.
Alternatively, you could create a userId
column in the Phone
table, storing the user to whom each phone belongs.
For instance, the following example creates a one-to-one relation between User
and Phone
using Prisma: