7 min read
Original source

Managing PostgreSQL relationships with Prisma

As applications grow, the number of different entities also increases. A crucial part of learning how to design a database is creating relationships between…

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 model User { id Int @default(autoincrement()) @id email String @unique name String password String }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 npm run generate-schemanpx prisma migrate dev --name user --preview-featurenpx prisma generateAbove, 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 { "name": "nestjs-prisma", "scripts": { // ... "generate-schema": "cat src/*/*.prisma > prisma/schema.prisma", "migrate": "npm run generate-schema && prisma migrate dev --preview-feature --name $npm_config_name && prisma generate", }, // ... }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 model Address { id Int @default(autoincrement()) @id street String city String country String }npm 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 model User { id Int @default(autoincrement()) @id email String @unique name String password String address Address? @relation(fields: [addressId], references: [id]) addressId Int? @unique } 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 model Address { id Int @default(autoincrement()) @id street String city String country String user User? }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.npm run migrate --name=address_user_relationBy 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 -- AlterTable ALTER TABLE "User" ADD COLUMN "addressId" INTEGER; -- CreateIndex CREATE UNIQUE INDEX "User_addressId_unique" ON "User"("addressId"); -- AddForeignKey ALTER 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 import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { CreateUserDto } from './dto/createUser.dto'; @Injectable() export class UsersService { constructor(private readonly prismaService: PrismaService) {} // ... async create(user: CreateUserDto) { const address = user.address; return this.prismaService.user.create({ data: { ...user, address: { create: address, }, }, }); } } 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 import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { CreateUserDto } from './dto/createUser.dto'; @Injectable() export class UsersService { constructor(private readonly prismaService: PrismaService) {} // ... async create(user: CreateUserDto) { const address = user.address; return this.prismaService.user.create({ data: { ...user, address: { create: address, }, }, include: { address: true, }, }); } } 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 model Post { id Int @default(autoincrement()) @id title String content String author User @relation(fields: [authorId], references: [id]) authorId Int }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 model User { id Int @default(autoincrement()) @id email String @unique name String password String address Address? @relation(fields: [addressId], references: [id]) addressId Int? posts Post[] }Let’s run the migration and see what SQL script Prisma generated for us.npm run migrate --name=user_post_relation migration.sql -- AlterTable ALTER TABLE "Post" ADD COLUMN "authorId" INTEGER NOT NULL; -- AddForeignKey ALTER 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 import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { CreatePostDto } from './dto/createPost.dto'; import { User } from '@prisma/client'; @Injectable() export class PostsService { constructor(private readonly prismaService: PrismaService) {} async createPost(post: CreatePostDto, user: User) { return this.prismaService.post.create({ data: { ...post, author: { connect: { id: user.id, }, }, }, }); } // ... } 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 model Category { id Int @id @default(autoincrement()) name String posts Post[] } postSchema.prisma model Post { id Int @default(autoincrement()) @id title String content String author User @relation(fields: [authorId], references: [id]) authorId Int categories Category[] }Now, let’s run the migration and check out the results.npm run migrate --name=category_post_relation migration.sql -- CreateTable CREATE TABLE "Category" ( "id" SERIAL NOT NULL, "name" TEXT NOT NULL, PRIMARY KEY ("id") ); -- CreateTable CREATE TABLE "_CategoryToPost" ( "A" INTEGER NOT NULL, "B" INTEGER NOT NULL ); -- CreateIndex CREATE UNIQUE INDEX "_CategoryToPost_AB_unique" ON "_CategoryToPost"("A", "B"); -- CreateIndex CREATE INDEX "_CategoryToPost_B_index" ON "_CategoryToPost

Managing PostgreSQL relationships with Prisma | NestJS.io