Evolve your schema for a SQL Server database in a Typescript project
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:
- Create a new model called
Tagwith the following fields:id: an auto-incrementing integer that will be the primary key for the modelname: a non-nullStringposts: an implicit many-to-many relation field that links to thePostmodel
- Update the
Postmodel with atagsfield with an implicit many-to-many relation field that links to theTagmodel
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:
- Create a new SQL migration file for the migration
- Apply the generated SQL migration to the database
- 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 [dbo].[Tag] (
[id] SERIAL NOT NULL,
[name] VARCHAR(255) NOT NULL,
CONSTRAINT [Tag_pkey] PRIMARY KEY ([id])
);
-- CreateTable
CREATE TABLE [dbo].[_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 [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_A_fkey] FOREIGN KEY ([A]) REFERENCES [dbo].[Post]([id]) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE [dbo].[_PostToTag] ADD CONSTRAINT [_PostToTag_B_fkey] FOREIGN KEY ([B]) REFERENCES [dbo].[Tag]([id]) ON DELETE CASCADE ON UPDATE CASCADE;
Congratulations, you just evolved your database with Prisma Migrate 🚀