Skip to content

Prisma ORM

安装

bash
npm i prisma --save-dev
npm i @prisma/client

# or
pnpm add prisma --save-dev
pnpm add @prisma/client

生成配置文件

bash
npx prisma init

# or
pnpm dlx prisma init

修改配置文件

  • prisma/schema.prisma 配置文件
prisma
// prisma配置
generator client {
  provider = "prisma-client"
  output   = "../generated/prisma" // 删除就默认路径
}

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

// 表结构
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}
  • 文件 .env 配置文件
txt
// mysql
DATABASE_URL="mysql://username:password@localhost:3306/database_name"

prisma client 配置生成

bash
# init为此次生成的描述,如add_user
npx prisma migrate dev --name init 

#or
pnpm dlx prisma migrate dev --name init

数据库权限

如报错:

Error: P3014

Prisma Migrate could not create the shadow database. Please make sure the database user has permission to create databases.

需要给数据库的用户相关权限

sql
GRANT CREATE, ALTER, DROP, REFERENCES ON *.* TO 'your_database_user'@'localhost';
FLUSH PRIVILEGES;

生成初始数据

教程:Prisma seed

相关命令

bash
# 如使用pnpm,请将 npx 改为 pnpm dlx

# 初始化
npx prisma init 

# 生成 Prisma 客户端(改配置需要执行)
npx prisma generate 

# 将定义的模型同步到数据库(改数据库模型执行)
npx prisma migrate dev --name init 

# 将迁移文件应用到生产数据库中(用于生产环境)
npx prisma migrate deploy

# 快速将模型同步到数据库中(生产环境不推荐)
npx prisma db push
npx prisma db push --accept-data-loss # 允许丢失数据

# 从现有的数据库拉取模型
npx prisma db pull