Nest.js Tutorial

Managing PostgreSQL relationships with Prisma

Marcin Wanago
JavaScriptNestJSTypeScript

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
1model User {
2  id        Int      @default(autoincrement()) @id
3  email     String   @unique
4  name      String
5  password  String
6}

Above, we use the @unique 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
1npm run generate-schema
1npx prisma migrate dev --name user --preview-feature
1npx prisma generate

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
1{
2  "name": "nestjs-prisma",
3  "scripts": {
4     // ...
5    "generate-schema": "cat src/*/*.prisma > prisma/schema.prisma",
6    "migrate": "npm run generate-schema && prisma migrate dev --preview-feature --name $npm_config_name && prisma generate",
7  },
8  // ...
9}

Now we need to run npm run migrate --name=user.

Above, NPM gets --name=user and gives us the access to it as $npm_config_name. We could do it with any variable name, such as --x=Hello and $npm_config_x.

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

addressSchema.prisma
1model Address {
2  id        Int      @default(autoincrement()) @id
3  street    String
4  city      String
5  country   String
6}
1npm run migrate --name=address

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 addressId to the user model.

userSchema.prisma
1model User {
2  id            Int         @default(autoincrement()) @id
3  email         String      @unique
4  name          String
5  password      String
6  address       Address?    @relation(fields: [addressId], references: [id])
7  addressId     Int?        @unique
8}
Using the ? sign above makes the address optional for the user.

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

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

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

addressSchema.prisma
1model Address {
2  id        Int      @default(autoincrement()) @id
3  street    String
4  city      String
5  country   String
6  user      User?
7}

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 user property as nullable.

1npm run migrate --name=address_user_relation

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 userId to the address model to invert the relation.

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

migration.sql
1-- AlterTable
2ALTER TABLE "User" ADD COLUMN "addressId" INTEGER;
3 
4-- CreateIndex
5CREATE UNIQUE INDEX "User_addressId_unique" ON "User"("addressId");
6 
7-- AddForeignKey
8ALTER TABLE "User" ADD FOREIGN KEY ("addressId") REFERENCES "Address"("id") ON DELETE SET NULL ON UPDATE CASCADE;

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 create property.

users.service.ts
1import { Injectable } from '@nestjs/common';
2import { PrismaService } from '../prisma/prisma.service';
3import { CreateUserDto } from './dto/createUser.dto';
4 
5@Injectable()
6export class UsersService {
7  constructor(private readonly prismaService: PrismaService) {}
8  
9  // ...
10  
11  async create(user: CreateUserDto) {
12    const address = user.address;
13    return this.prismaService.user.create({
14      data: {
15        ...user,
16        address: {
17          create: address,
18        },
19      },
20    });
21  }
22}

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

users.service.ts
1import { Injectable } from '@nestjs/common';
2import { PrismaService } from '../prisma/prisma.service';
3import { CreateUserDto } from './dto/createUser.dto';
4 
5@Injectable()
6export class UsersService {
7  constructor(private readonly prismaService: PrismaService) {}
8 
9  // ...
10 
11  async create(user: CreateUserDto) {
12    const address = user.address;
13    return this.prismaService.user.create({
14      data: {
15        ...user,
16        address: {
17          create: address,
18        },
19      },
20      include: {
21        address: true,
22      },
23    });
24  }
25}

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
1model Post {
2  id        Int      @default(autoincrement()) @id
3  title     String
4  content   String
5  author    User     @relation(fields: [authorId], references: [id])
6  authorId  Int
7}

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
1model User {
2  id            Int         @default(autoincrement()) @id
3  email         String      @unique
4  name          String
5  password      String
6  address       Address?     @relation(fields: [addressId], references: [id])
7  addressId     Int?
8  posts         Post[]
9}

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

1npm run migrate --name=user_post_relation
migration.sql
1-- AlterTable
2ALTER TABLE "Post" ADD COLUMN     "authorId" INTEGER NOT NULL;
3 
4-- AddForeignKey
5ALTER TABLE "Post" ADD FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

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 PostsService in a way that allows us to assign an author to the post.

posts.service.ts
1import { Injectable } from '@nestjs/common';
2import { PrismaService } from '../prisma/prisma.service';
3import { CreatePostDto } from './dto/createPost.dto';
4import { User } from '@prisma/client';
5 
6@Injectable()
7export class PostsService {
8  constructor(private readonly prismaService: PrismaService) {}
9 
10  async createPost(post: CreatePostDto, user: User) {
11    return this.prismaService.post.create({
12      data: {
13        ...post,
14        author: {
15          connect: {
16            id: user.id,
17          },
18        },
19      },
20    });
21  }
22 
23  // ...
24}
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 @prisma/client to get the user model interface. With the connect 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
1model Category {
2  id    Int    @id @default(autoincrement())
3  name  String
4  posts Post[]
5}
postSchema.prisma
1model Post {
2  id        Int      @default(autoincrement()) @id
3  title     String
4  content   String
5  author    User  @relation(fields: [authorId], references: [id])
6  authorId  Int
7  categories Category[]
8}

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

1npm run migrate --name=category_post_relation
migration.sql
1-- CreateTable
2CREATE TABLE "Category" (
3    "id" SERIAL NOT NULL,
4    "name" TEXT NOT NULL,
5 
6    PRIMARY KEY ("id")
7);
8 
9-- CreateTable
10CREATE TABLE "_CategoryToPost" (
11    "A" INTEGER NOT NULL,
12    "B" INTEGER NOT NULL
13);
14 
15-- CreateIndex
16CREATE UNIQUE INDEX "_CategoryToPost_AB_unique" ON "_CategoryToPost"("A", "B");
17 
18-- CreateIndex
19CREATE INDEX "_CategoryToPost_B_index" ON "_CategoryToPost"("B");
20 
21-- AddForeignKey
22ALTER TABLE "_CategoryToPost" ADD FOREIGN KEY ("A") REFERENCES "Category"("id") ON DELETE CASCADE ON UPDATE CASCADE;
23 
24-- AddForeignKey
25ALTER TABLE "_CategoryToPost" ADD FOREIGN KEY ("B") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE;

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
1import { Injectable } from '@nestjs/common';
2import { PrismaService } from '../prisma/prisma.service';
3import { CreatePostDto } from './dto/createPost.dto';
4import { User } from '@prisma/client';
5 
6@Injectable()
7export class PostsService {
8  constructor(private readonly prismaService: PrismaService) {}
9 
10  async createPost(post: CreatePostDto, user: User) {
11    const categories = post.categoryIds?.map((category) => ({
12      id: category,
13    }));
14 
15    return this.prismaService.post.create({
16      data: {
17        title: post.title,
18        content: post.content,
19        author: {
20          connect: {
21            id: user.id,
22          },
23        },
24        categories: {
25          connect: categories,
26        },
27      },
28      include: {
29        categories: true,
30      },
31    });
32  }
33 
34  // ...
35}

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.