Skip to main content

Evolve your schema

Add a Tag model to your schema

In this section, you will evolve your Prisma schema and then generate and apply the migration to your database with prisma migrate dev.

For the purpose of this guide, we'll make the following changes to the Prisma schema:

  1. Create a new model called Tag with the following fields:
    • id: an auto-incrementing integer that will be the primary key for the model
    • name: a non-null String
    • posts: an implicit many-to-many relation field that links to the Post model
  2. Update the Post model with a tags field with an implicit many-to-many relation field that links to the Tag model

Once you've made the changes to your schema, your schema should resemble the one below:

prisma/schema.prisma
model Post {
id Int @id @default(autoincrement())
title String @db.VarChar(255)
createdAt DateTime @default(now()) @db.Timestamp(6)
content String?
published Boolean @default(false)
authorId Int
user User @relation(fields: [authorId], references: [id])
tags Tag[]
}

model Profile {
id Int @id @default(autoincrement())
bio String?
userId Int @unique
user User @relation(fields: [userId], references: [id])
}

model User {
id Int @id @default(autoincrement())
name String? @db.VarChar(255)
email String @unique @db.VarChar(255)
post Post[]
profile Profile?
}

model Tag {
id Int @id @default(autoincrement())
name String
posts Post[]
}

To apply your Prisma schema changes to your database, use the prisma migrate dev CLI command:

npx prisma migrate dev --name tags-model

This command will:

  1. Create a new SQL migration file for the migration
  2. Apply the generated SQL migration to the database
  3. Regenerate Prisma Client

The following migration will be generated and saved in your prisma/migrations folder:

prisma/migrations/TIMESTAMP_tags_model.sql
-- CreateTable
CREATE TABLE Tag (
id SERIAL NOT NULL,
name VARCHAR(255) NOT NULL,

CONSTRAINT Tag_pkey PRIMARY KEY (id)
);

-- CreateTable
CREATE TABLE _PostToTag (
A INTEGER NOT NULL,
B INTEGER NOT NULL
);

-- CreateIndex
CREATE UNIQUE INDEX _PostToTag_AB_unique ON _PostToTag(A, B);

-- CreateIndex
CREATE INDEX _PostToTag_B_index ON _PostToTag(B);

-- AddForeignKey
ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_A_fkey FOREIGN KEY (A) REFERENCES Post(id) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE _PostToTag ADD CONSTRAINT _PostToTag_B_fkey FOREIGN KEY (B) REFERENCES Tag(id) ON DELETE CASCADE ON UPDATE CASCADE;

Congratulations, you just evolved your database with Prisma Migrate 🚀