文章
prisma基本使用
初始化
npx prisma init
修改配置文件
/prisma/shcema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
添加.env环境变量
DATABASE_URL="mysql://backend_user:BackendUser@localhost:3306/backend_db"
添加测试模型
/prisma/shcema.prisma 添加如下模型信息
model Test {
id Int @id @default(autoincrement())
name String @db.VarChar(255)
desc String?
number Int
isPublished Boolean
}
将模型推送到mysql
npx prisma db push
prisma studio
npx prisma studio
安装prisma客户端
npm install @prisma/client
使用prisma客户端
/src/lib/client.ts
import { PrismaClient } from '@prisma/client'
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }
export const prisma = globalForPrisma.prisma || new PrismaClient()
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma