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…
April 5, 2021
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.
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=userand gives us the access to it as$npm_config_name. We could do it with any variable name, such as--x=Helloand$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=addressDefining 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
addressIdfield from the user model is the foreign key and points to an address, - the
idfield from the address model that we want to reference with theaddressIdfield.
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_relationmigration.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,
},
},
},
})
} // ...
}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_relationmigration.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"("B");
-- AddForeignKey
ALTER TABLE "_CategoryToPost" ADD FOREIGN KEY ("A") REFERENCES "Category"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER 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#
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) {
const categories = post.categoryIds?.map((category) => ({
id: category,
}))
return this.prismaService.post.create({
data: {
title: post.title,
content: post.content,
author: {
connect: {
id: user.id,
},
},
categories: {
connect: categories,
},
},
include: {
categories: true,
},
})
} // ...
}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.