6.3.1-prisma-schema
Create by fall on 26 Jul 2025
Recently revised in 23 Jun 2025
Prisma Schema
是 prisma 的主要配置方法,由以下几个部分组成
- 数据源:
datasource
指定根据数据模型生成哪些客户端 - 生成器:
generator
指定根据数据模型生成哪些客户端 - 数据模型定义:
data model
Prisma CLI 按以下顺序在以下位置查找 Prisma Schema:
datasource db {
provider = "mongodb"
url = env("DATABASE_URL") // 使用 env 中的 DATABASE_URL 变量
}
// generator 决定了当你运行 prisma generate 命令时,在哪里创建文件
generator client {
provider = "prisma-client-js"
// output = "./generated/prisma-client-js" // 可选,自定义输出的位置
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId // prisma 不支持 _开头的关键字,因此使用 @map("_id") 映射到 Mongo 上
slug String @unique
title String
body String
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
comments Comment[]
}
命令
prisma generate
:从 Prisma 架构中读取上述所有信息,以生成正确的数据源客户端代码(例如 Prisma 客户端)。
prisma migrate dev
:读取数据源和数据模型定义以创建新的迁移。
注释
两种注释类型
// comment
:为了读者的清晰度/// comment
:作为抽象节点的注释
/// This comment will get attached to the `User` node in the AST
model User {
/// This comment will get attached to the `id` node in the AST
id Int @default(autoincrement())
// This comment is just for you
weight Float /// This comment gets attached to the `weight` node
}
// This comment is just for you. It will not
// show up in the AST.
/// This comment will get attached to the
/// Customer node.
model Customer {}
多文件 prisma
使用多文件 prisma 时,你必须明确指出包含 .prisma
文件的路径,包含 datasource
数据模型定义
关系型数据库
model NavLink {
id Int @id @default(autoincrement())
// @id 定义该 model 上的唯一值,可以使用 @default 属性使用方法自动生成一个 ID
// 例如 autoincrement() cuid() uuid() ulid() 等
categoryId String
name String
// 网站url
href String
desc String // 没有 ? 时,为必填字段,通过底层数据库中的 NOT NULL 约束表示。
logo String? // ? 将字段设置为可选,默认值为 null
tag NavTag[] // [] 可以将字段设定为列表
// 页面浏览次数
view Int @default(0)
star Int @default(0)
// 审核状态 1 审核中 2 拒绝 3 通过
status Int
// 访问状态 1 正常访问 2 需要代理 3 网站已停用
accessState Int
}
model NavTag {
id Int @id @default(autoincrement())
name String
createTime DateTime
NavLink NavLink[]
}
enum LinkState {
CHECK
REJECT
PASS
}
// 根据不同的底层,会有不同的类型属性
model Post {
id Int @id
// postgres 使用 @db.Boolean 表示 boolean,mysql 使用 @db.TinyInt(1)
title String @db.VarChar(200)
content String
}
关系
// 一个帖子对应多个评论,一个评论对应一个帖子
model Post {
id Int @id @default(autoincrement())
// Other fields
comments Comment[] // A post can have many comments
}
model Comment {
id Int
// Other fields
post Post? @relation(fields: [postId], references: [id]) // A comment can have one post
postId Int?
}