Core Concepts
Models
Models represent entities in your application domain:- Maps to a database table
- Defines fields with types and constraints
- Can have relations to other models
Fields
Fields are the properties of a model:Data Types
Scalar Types
Prisma provides built-in scalar types:- String
- Numbers
- Boolean
- DateTime
- Json
- Bytes
Text data of any length:
Composite Types
MongoDB supports embedded documents:Relations
Relations define connections between models.One-to-Many Relations
One record relates to many records:Post.authoris the relation field (not stored in DB)Post.authorIdis the foreign key (stored in DB)User.postsis the back-relation (virtual field)
One-to-One Relations
One record relates to exactly one other record:@unique constraint on the foreign key makes it one-to-one.
Many-to-Many Relations
Many records relate to many other records.Implicit Many-to-Many
Prisma manages the join table:Explicit Many-to-Many
You manage the join table for additional fields:Self-Relations
A model can relate to itself:Multiple Relations Between Same Models
Use named relations:Real-World Example
Here’s a complete e-learning platform data model:Constraints and Indexes
Primary Keys
Every model needs a unique identifier:Unique Constraints
Enforce uniqueness:Indexes
Improve query performance:Foreign Key Actions
Control cascade behavior:Cascade- Delete/update related recordsRestrict- Prevent if related records existNoAction- Database default behaviorSetNull- Set foreign key to NULLSetDefault- Set foreign key to default value
Default Values
Set default values for fields:autoincrement()- Auto-incrementing integernow()- Current timestampuuid()- UUID v4cuid()- CUIDdbgenerated("expression")- Database-generated value
Field Validation
While Prisma doesn’t provide built-in validation, you can use:Database-Level Constraints
Application-Level Validation
Naming Conventions
Model Names
Field Names
Map to Database Names
If your database uses different conventions:Best Practices
1. Always Use Timestamps
2. Index Foreign Keys
3. Use Enums for Fixed Sets
4. Normalize Data Appropriately
5. Use Cascade Deletes Carefully
Next Steps
Prisma Schema
Deep dive into schema syntax
Relations
Advanced relation patterns
Migrations
Apply schema changes to database
Prisma Client
Query your data model