How to Create a Data Model with Prisma: A Step-by-Step Guide
Prisma is a modern ORM for Node.js and TypeScript that simplifies database interactions. Its core is the schema.prisma file where you define your data models. This tutorial walks you through creating a data model from scratch, covering key concepts like fields, relations, and migrations.
First, initialize Prisma in your project using npx prisma init. This generates the schema file and a .env for your database connection string (e.g., PostgreSQL, SQLite). Open prisma/schema.prisma to start modeling.
1. Defining Your First Model
Add a model block with a PascalCase name (e.g., User). Inside, declare fields with name, type, and optional attributes.
- Fields:
id Int @id @default(autoincrement())– creates an auto-incrementing primary key. - Other types:
String,Boolean,DateTime,Float. - Modifiers:
@uniquefor unique constraints;@default(...)for default values.
2. Adding Relations Between Models
Prisma uses relational fields to connect models. For example, a User can have many Post records.
- One-to-many: In
User, addposts Post[](list). InPost, addauthor User @relation(fields: [authorId], references: [id])andauthorId Int. - Many-to-many: Use implicit relations by declaring a list on both sides (e.g.,
tags Tag[]andposts Post[]).
3. Running Migrations
Once your models are complete, sync them to your database:
- Run
npx prisma migrate dev --name init. This generates SQL files and applies them. - Check your database (via a GUI or CLI) – the tables should match your schema.
- Use
npx prisma generateto create the Prisma Client, which provides type-safe queries.
Conclusion: You’ve now created a data model with Prisma. The schema file is your single source of truth – update it and run migrations to evolve your database. Start querying with prisma.user.findMany() and build your application.