schema.prisma file in Prisma
Here’s how Prisma identifies and utilizes model definitions:
Structure of Prisma Schema
In your schema.prisma file, you define your database schema using the Prisma schema definition language. This file typically includes:
-
Data Models: Each
modelblock defines a database table or collection, along with its fields and relationships. -
Relations:
@relationdirectives define relationships between models, such as one-to-one, one-to-many, or many-to-many relationships. -
Datasource: This tells prisma which database to connect to
Example schema.prisma
Here’s a simplified example of a schema.prisma file with two models (User and Post):
// schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
username String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String
authorId Int
author User @relation(fields: [authorId], references: [id])
}
How Prisma Uses Models
Prisma uses the models defined in your schema.prisma file to generate a Prisma Client. Here’s how it works:
-
Model Definitions: Each
modelblock inschema.prismadefines a table (or collection) in your database. -
Generated Prisma Client: When you run
npx prisma generate, Prisma inspects yourschema.prismafile and generates a TypeScript/JavaScript client (PrismaClient) based on your model definitions. -
Model Usage in Code:
-
You import and use the generated
PrismaClientin your Node.js application to interact with your database. For example:const { PrismaClient } = require('@prisma/client'); const prisma = new PrismaClient(); async function createUser(username) { const user = await prisma.user.create({ data: { username, }, }); return user; }Here,
prisma.userrefers to theUsermodel defined in yourschema.prisma.
-
-
Naming Convention: Prisma expects the name of the model in your Prisma schema to match the corresponding table (or collection) name in your database. This convention ensures that Prisma can correctly map operations to the appropriate database entities.