Prisma 模式设计与迁移
使用 Prisma 模式语言设计数据库模式,并管理数据库迁移。
Prisma 模式设计与迁移 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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 aDateTimefield 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:
- Compares your
schema.prismato the database. - Generates a new migration file (SQL) if there are changes.
- Applies the new migration to your development database.
Try it after making a change to your schema:
npx prisma migrate dev --name added_user_profileApplying 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 pushQuick 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.prismafile 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 模式设计与迁移」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
「Prisma 模式设计与迁移」这节课中我会学到什么?
使用 Prisma 模式语言设计数据库模式,并管理数据库迁移。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack Web Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「Prisma 模式设计与迁移」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。