0Pricing
Next.js 15 Fullstack Web Apps · Урок

Проектирование схемы Prisma и миграции

Спроектируйте схему базы данных с помощью языка схем Prisma и управляйте миграциями базы данных.

«Проектирование схемы Prisma и миграции» — бесплатный урок Next.js 15 Fullstack Web Apps на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Next.js 15 Fullstack Web Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Prisma Schema: Your Database Blueprint

Welcome back! In this lesson, we'll dive into designing your database schema using Prisma Schema Language and managing changes with migrations.

The schema.prisma file is the heart of your Prisma setup. It's a single source of truth for your database schema and how your application models interact with it.

The Core Schema Blocks

Every schema.prisma file starts with two main blocks: datasource and generator.

  • datasource: Defines your database connection (e.g., PostgreSQL, MySQL, SQLite).
  • generator: Specifies which Prisma Client to generate, allowing you to interact with your database in a type-safe way.

Here's a basic structure:

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

Defining Models: Your Data Structure

After the core blocks, you define your models. A Prisma model maps directly to a table in your database and represents the structure of your data.

The model keyword is used, followed by the model's name (singular, PascalCase, e.g., User or Product).

model User {
  id    String @id @default(uuid())
  email String @unique
  name  String?
}

Fields and Data Types

Inside each model, you define fields, which correspond to columns in your database table. Each field has a name and a data type.

Prisma supports common scalar types like String, Int, Boolean, DateTime, Float, Json, and more. For example, id is often a String or Int.

model Product {
  id          Int      @id @default(autoincrement())
  name        String
  description String?
  price       Float
  published   Boolean  @default(false)
  createdAt   DateTime @default(now())
}

Field Modifiers and Attributes

Fields can have modifiers and attributes to add extra meaning or constraints:

  • ? (Optional): Makes a field nullable.
  • [] (List): Indicates a list of values (e.g., String[]).
  • @id: Marks a field as the primary key.
  • @unique: Ensures all values in this field are unique.
  • @default(): Sets a default value.
  • @updatedAt: Automatically updates a DateTime field on every record update.
model Post {
  id        String    @id @default(uuid())
  title     String
  content   String?
  published Boolean   @default(false)
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
}

Connecting Data: Relations

Databases are all about related data! Prisma makes it easy to define relationships between your models, like a user having many posts (one-to-many).

You define a relation by linking fields between models using the @relation attribute. This attribute takes arguments like fields (the foreign key) and references (the primary key it refers to).

model User {
  id        String    @id @default(uuid())
  email     String    @unique
  name      String?
  posts     Post[]    // A user can have many posts
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
}

model Post {
  id        String    @id @default(uuid())
  title     String
  content   String?
  published Boolean   @default(false)
  author    User?     @relation(fields: [authorId], references: [id]) // Relation to User
  authorId  String?   // Foreign key for the User
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
}

Evolving Your Database: Migrations

As your application grows, your database schema will change. Migrations are how Prisma tracks these changes and applies them to your actual database in a controlled, versioned way.

Prisma Migrate generates SQL files based on the differences between your schema.prisma and your current database state, ensuring your database evolves predictably.

Generating Your First Migration

To create a new migration, you use the Prisma CLI command npx prisma migrate dev. You should give your migration a descriptive name.

This command does three things:

  1. Compares your schema.prisma to the database.
  2. Generates a new migration file (SQL) if there are changes.
  3. Applies the new migration to your development database.

Try it after making a change to your schema:

npx prisma migrate dev --name added_user_profile

Applying Migrations & Schema Sync

Besides prisma migrate dev for development, there are other commands:

  • npx prisma migrate deploy: Applies all pending migrations to the database. This is typically used in production environments.
  • npx prisma db push: Pushes the current schema state to the database without creating a migration file. Useful for rapid prototyping in development when you don't need migration history.

Choose the right command for your workflow!

npx prisma migrate deploy

npx prisma db push

Quick Check: Schema Updates

You've just added a new field role to your User model in schema.prisma and want to apply this change to your development database while also creating a migration file to track this change. Which command should you use?

Schema & Migrations: Key Takeaways

Great job! You've learned how to design your database with Prisma Schema Language and manage its evolution with migrations.

  • The schema.prisma file is your single source of truth for database structure.
  • Models define tables, and fields define columns with various types and attributes.
  • Relations connect your models, reflecting real-world data links.
  • Prisma Migrate helps you track and apply schema changes reliably across environments.

Next, we'll learn how to perform CRUD operations (Create, Read, Update, Delete) using the Prisma Client.

Часто задаваемые вопросы

Урок «Проектирование схемы Prisma и миграции» бесплатный?

Да — полный текст урока «Проектирование схемы Prisma и миграции» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Next.js 15 Fullstack Web Apps, подпишись на CoddyKit PRO. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Чему я научусь в уроке «Проектирование схемы Prisma и миграции»?

Спроектируйте схему базы данных с помощью языка схем Prisma и управляйте миграциями базы данных. Ты практикуешь Next.js 15 Fullstack Web Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Next.js 15 Fullstack Web Apps?

Предыдущий опыт не требуется. Next.js 15 Fullstack Web Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Проектирование схемы Prisma и миграции»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Next.js 15 Fullstack Web Apps?

Да. Каждый урок Next.js 15 Fullstack Web Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Введение в Prisma ORM
  2. Проектирование схемы Prisma и миграции
  3. Операции CRUD с Prisma Client
  4. Связи и расширенные запросы с Prisma
← Назад к Next.js 15 Fullstack Web Apps