API with NestJS #33. Managing PostgreSQL relationships with Prisma

JavaScript NestJS TypeScript

This entry is part 33 of 33 in the API with NestJS

As applications grow, the number of different entities also increases. A crucial part of learning how to design a database is creating relationships between them. This is because our entities will often relate to each other in some way.

Relational databases such as PostgreSQL are an industry standard for quite some time now. Although there are NoSQL alternatives such as MongoDB, SQL might still be considered a better choice, especially for structured data that contains a lot of relations.

In this article, we learn about various types of relationships and implement them with Postgres. Instead of using TypeORM as we did in the seventh part of this series, we use Prisma.

Throughout the article, we often use functionalities developed in other parts of this series. If you want to see the full code, you can find it in this repository.

One-To-One

The simplest relationship is called one-to-one. Here, a row from the first table matches just one row from the second table and vice versa.

To represent it, let’s create the user and the address.

userSchema.prisma

Above, we use the attribute. It creates a constraint, making it impossible to create two users with the same email.

After creating the above schema, let’s generate a migration for it.

If you want to know more about this process, check out API with NestJS #32. Introduction to Prisma with PostgreSQL

Above, we can see that migrating and generating a new Prisma Client takes us three commands. Instead of that, let’s create a command that merges those.

package.json

Now we need to run .

Above, NPM gets and gives us the access to it as . We could do it with any variable name, such as and .

Now we can do the same thing when creating the address model.

addressSchema.prisma

Defining the relationship

To define the relationship, one of the sides of the relationship needs to hold the other side’s id. In our example, we add the to the user model.

userSchema.prisma

Using the sign above makes the address optional for the user.

Above, we’ve also used the attribute. We pass two arguments to it:

  • the field from the user model is the foreign key and points to an address,
  • the field from the address model that we want to reference with the field.

We also need to add information about the relation to the address model.

addressSchema.prisma

The address table in the database does not hold any information tying it to a certain user. Therefore, there is a possibility that a certain address is not related to any user. Because of that, we need to mark the property as nullable.

By doing all of the above, we achieve the following:

  • the user can have an address but does not need to,
  • the address can but does not have to be associated with a user.

Alternatively, we could also add the to the address model to invert the relation.

Let’s look into how Prisma generates the above migration:

migration.sql

The crucial thing above is that we create a unique index. Because of that, there can’t be two users pointing to the same address.

Creating related records

With Prisma, we can easily create both a user entity and the address and create a relationship between them at once. To do that, we need to use the property.

users.service.ts

We can see that we didn’t receive the full address in the response, just the id. We can improve that by using the property.

users.service.ts

One-to-Many and Many-To-One

With the One-To-Many relationship, a row from the first table can be related to multiple rows from the second table. The row from the second table can be linked to just one row of the first table, though.

A good example could be posts and users. A user can write multiple posts in our implementation, but a post is authored by just a single user.

postSchema.prisma

Above, we store the information about the author in the post model. We can see that a post can have only one author.

We also need to add information about the relationship to the user model.

userSchema.prisma

Let’s run the migration and see what SQL script Prisma generated for us.

migration.sql

Above, we can see that we don’t use the unique indexes in the case of the One-To-Many relationship. This is how One-To-Many differs from One-To-One. Because of that, we achieve the following:

  • the user can have zero or more posts,
  • the post needs to have an author.

Let’s modify our in a way that allows us to assign an author to the post.

posts.service.ts

In this article, we depend on the authentication functionality described in API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies

Above, the crucial part is that we need to import it from to get the user model interface. With the property, we attach the existing user to the newly created post.

Many-to-Many

With the Many-To-Many relationship, a row from the first table can relate to the second table’s multiple rows and vice versa.

A good example might be a post that can belong to multiple categories. A category, on the other hand, can contain multiple posts.

The easiest way to define a Many-To-Many relationship in Prisma is to create a so-called implicit relationship.

categorySchema.prisma

postSchema.prisma

Now, let’s run the migration and check out the results.

migration.sql

Above, we can see quite a lot going on. When migrating, Prisma defined a new table called _CategoryToPost. This is because to create a Many-To-Many relationship, we need to define a separate table.

In the _CategoryToPost table, the A column points to a row in the Category table. Let’s see the following example:

The above means that the category with id 1 is in relationship with the post with id 3.

As an alternative to doing an implicit Many-To-Many relationship, we could create the additional table manually. For an example, visit the official documentation.

Let’s also create an easy way to attach categories to the newly created posts.

posts.service.ts

Above, we create an array of category ids based on the input sent by the user.

Summary

In this article, we’ve covered managing relationships in PostgreSQL with Prisma. It included learning about various types of relationships: One-To-One, One-To-Many, and Many-To-Many. We’ve also learned how to deal with them when creating new records in the database and querying them. So far, Prisma proves to be a capable alternative to TypeORM.

Series Navigation<< API with NestJS #32. Introduction to Prisma with PostgreSQL
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments