Prisma

 

2024-03-02

安装

通过 npm 安装:

Terminal window
1
npm install prisma --save-dev
2
3
# 调用 CLI
4
npx prisma

通过 bun 安装:

Terminal window
1
bunx prisma

使用

在现有项目目录中执行:

Terminal window
1
npx prisma init

执行后会做两件事:

  1. 在 prisma 目录内创建 schema.prisma 文件
  2. 在根目录新增 .env 文件,用于定义环境变量

连接数据库

修改==prisma/schema.prisma==文件:

1
datasource db {
2
provider = "postgresql"
3
url = env("DATABASE_URL")
4
}

在==.env==中添加数据库连接信息:

1
DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
2
3
# PostgreSQL (schema 可使用默认)
4
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA

创建

在 schema.prisma 创建数据模型:

1
model Post {
2
id Int @id @default(autoincrement())
3
createdAt DateTime @default(now())
4
updatedAt DateTime @updatedAt
5
title String @db.VarChar(255)
6
content String?
7
published Boolean @default(false)
8
author User @relation(fields: [authorId], references: [id])
9
authorId Int
10
}
11
12
model Profile {
13
id Int @id @default(autoincrement())
14
bio String?
15
user User @relation(fields: [userId], references: [id])
16
userId Int @unique
17
}
18
19
model User {
20
id Int @id @default(autoincrement())
21
email String @unique
22
name String?
23
posts Post[]
24
profile Profile?
25
}

根据模型在数据库中生成对应表:

Terminal window
1
npx prisma migrate dev --name init

写入

读取