跳至主要內容

從 CLI 開始

本頁面提供了在執行 prisma init --db 後使用 Prisma Postgres 的逐步指南。

  1. 使用 Prisma ORM 建立 TypeScript 應用程式
  2. 遷移您的資料庫結構
  3. 從 TypeScript 查詢您的資料庫

先決條件

本指南假設您已經透過 prisma init --db 設定好 Prisma Postgres 實例。

npx prisma@latest init --db
顯示CLI結果

當此指令終止後

  • 您已登入 Prisma Data Platform。
  • 新的 Prisma Postgres 實例已建立。
  • prisma/ 資料夾已建立,其中包含一個空的 schema.prisma 檔案。
  • DATABASE_URL 環境變數已在 .env 檔案中設定。
  • prisma.config.ts 檔案已使用預設配置建立。

1. 組織您的專案目錄

注意

如果您是在預期的專案資料夾內執行 prisma init --db 指令,您可以跳過此步驟並前往下一節

如果您是在預期專案目錄之外(例如在家目錄或其他位置)執行該指令,您需要將產生的 prisma 資料夾和 .env 檔案移動到專用的專案目錄中。

建立一個新資料夾(例如 hello-prisma)作為您存放專案的地方,並將必要的檔案移入其中。

mkdir hello-prisma
mv .env ./hello-prisma/
mv prisma ./hello-prisma/

進入您的專案資料夾。

cd ./hello-prisma

現在您的專案位於正確的位置,請繼續進行設定。

2. 設定您的專案

2.1. 設定 TypeScript

初始化 TypeScript 專案並將 Prisma CLI 加入為開發依賴項。

npm init -y
npm install typescript tsx @types/node @types/pg --save-dev

這將會建立一個包含 TypeScript 應用程式初始設定的 package.json 檔案。

接下來,在專案中透過 tsconfig.json 檔案初始化 TypeScript。

npx tsc --init

2.2. 設定 ESM 支援

更新 tsconfig.json 以確保 ESM 相容性

tsconfig.json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "node",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"ignoreDeprecations": "6.0"
}
}

更新 package.json 以啟用 ESM

package.json
{
"type": "module",
}

2.3. 設定 Prisma ORM

安裝使用 Prisma Postgres 所需的依賴項。

npm install prisma --save-dev
npm install @prisma/client @prisma/adapter-pg pg dotenv

以下是各個套件的功能說明

  • prisma - 用於執行 prisma migrateprisma generate 等指令的 Prisma CLI。
  • @prisma/client - 用於查詢資料庫的 Prisma Client 函式庫
  • @prisma/adapter-pg - 將 Prisma Client 連接至資料庫的 node-postgres 驅動程式轉接器
  • pg - node-postgres 資料庫驅動程式
  • @types/pg - node-postgres 的 TypeScript 型別定義
  • dotenv - 從您的 .env 檔案載入環境變數

2.4. 檢閱產生的 prisma.config.ts

prisma init --db 指令會自動建立一個 prisma.config.ts 檔案,內容如下:

prisma.config.ts
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'

export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})

2.5. 建立查詢資料庫的指令碼

在根目錄中建立一個 index.ts 檔案,這將用於透過 Prisma ORM 查詢您的應用程式。

touch index.ts

3. 遷移資料庫結構

更新您的 prisma/schema.prisma 檔案以包含 UserPost 模型。

prisma/schema.prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}

datasource db {
provider = "postgresql"
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}

model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}

加入模型後,使用 Prisma Migrate 遷移您的資料庫。

npx prisma migrate dev --name init

此指令會根據您的 Schema 建立資料庫資料表。

現在執行以下指令來生成 Prisma Client

npx prisma generate

4. 使用 Prisma ORM 發送查詢

4.1. 實例化 Prisma Client

建立一個 lib/prisma.ts 檔案,使用驅動程式適配器(driver adapter)來實例化 Prisma Client。

lib/prisma.ts
import "dotenv/config";
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '../generated/prisma/client'

const connectionString = `${process.env.DATABASE_URL}`

const adapter = new PrismaPg({ connectionString })
const prisma = new PrismaClient({ adapter })

export { prisma }
提示

如果您需要透過邊緣執行環境 (Edge Runtime,如 Cloudflare Workers、Vercel Edge Functions 等) 以 HTTP 方式查詢資料庫,請使用 Prisma Postgres 無伺服器驅動程式 (serverless driver)

4.2. 撰寫您的第一個查詢

將以下樣板程式碼貼到 index.ts 中。

index.ts
import { prisma } from './lib/prisma'

async function main() {
// ... you will write your Prisma ORM queries here
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

此程式碼包含一個在指令碼末尾呼叫的 main 函數。它同時也會實例化 PrismaClient,您將使用它向您的資料庫發送查詢。

4.3. 建立新的 User 記錄

讓我們從一個簡單的查詢開始,在資料庫中建立一個新的 User 記錄,並將產生的物件記錄到主控台。將以下程式碼加入您的 index.ts 檔案中。

index.ts
import { prisma } from './lib/prisma'

async function main() {
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
},
})
console.log(user)
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

接下來,使用以下指令執行指令碼:

npx tsx index.ts
顯示CLI結果
{ id: 1, email: 'alice@prisma.io', name: 'Alice' }

做得好,您剛剛使用 Prisma Postgres 建立了您的第一筆資料庫記錄!🎉

4.4. 檢索所有 User 記錄

Prisma ORM 提供了多種查詢方式來從您的資料庫讀取資料。在本節中,您將使用 findMany 查詢,它會傳回給定模型在資料庫中的所有記錄。

刪除先前的 Prisma ORM 查詢,並改為加入新的 findMany 查詢。

index.ts
import { prisma } from './lib/prisma'

async function main() {
const users = await prisma.user.findMany()
console.log(users)
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

再次執行指令碼。

npx tsx index.ts
顯示CLI結果
[{ id: 1, email: 'alice@prisma.io', name: 'Alice' }]

請注意,現在主控台中的單個 User 物件已被方括號包圍。這是因為 findMany 傳回了一個包含單個物件的陣列。

4.5. 探索關聯查詢

Prisma ORM 的主要功能之一是處理關聯的便利性。在本節中,您將學習如何透過巢狀寫入查詢來同時建立 UserPost 記錄。隨後,您將看到如何使用 include 選項從資料庫檢索關聯。

首先,調整您的指令碼以包含巢狀查詢。

index.ts
import { prisma } from './lib/prisma'

async function main() {
const user = await prisma.user.create({
data: {
name: 'Bob',
email: 'bob@prisma.io',
posts: {
create: [
{
title: 'Hello World',
published: true
},
{
title: 'My second post',
content: 'This is still a draft'
}
],
},
},
})
console.log(user)
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

透過再次執行指令碼來運行該查詢。

npx tsx index.ts
顯示CLI結果
{ id: 2, email: 'bob@prisma.io', name: 'Bob' }

為了同時檢索屬於 UserPost 記錄,您可以透過 posts 關聯欄位使用 include 選項。

index.ts
import { prisma } from './lib/prisma'

async function main() {
const usersWithPosts = await prisma.user.findMany({
include: {
posts: true,
},
})
console.dir(usersWithPosts, { depth: null })
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

再次執行指令碼以查看巢狀讀取查詢的結果。

npx tsx index.ts
顯示CLI結果
[
{ id: 1, email: 'alice@prisma.io', name: 'Alice', posts: [] },
{
id: 2,
email: 'bob@prisma.io',
name: 'Bob',
posts: [
{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 2
},
{
id: 2,
title: 'My second post',
content: 'This is still a draft',
published: false,
authorId: 2
}
]
}
]

這一次,您會看到列印出兩個 User 物件。它們都有一個 posts 欄位(對於 "Alice" 來說是空的,而對於 "Bob" 來說則包含兩個 Post 物件),代表與它們相關聯的 Post 記錄。

後續步驟

您剛剛初步體驗了基本的 Prisma Postgres 設定。如果您想探索更複雜的查詢,例如新增快取功能,請查看官方的快速入門

在 Prisma Studio 中查看和編輯資料

Prisma ORM 附帶一個內建的 GUI,用於查看和編輯資料庫中的資料。您可以使用以下指令開啟它:

npx prisma studio --config ./prisma.config.ts

透過 Prisma Postgres,您也可以直接在以下位置使用 Prisma Studio:透過在您的專案中選擇 Studio 分頁。

使用 Next.js 建立全端應用程式

了解如何在全端應用程式中使用 Prisma Postgres。

探索可直接執行的範例

查看 GitHub 上的 prisma-examples 儲存庫,看看 Prisma ORM 如何與您喜愛的程式庫搭配使用。該儲存庫包含 Express、NestJS、GraphQL 的範例,以及 Next.js 和 Vue.js 的全端範例等等。

這些範例預設使用 SQLite,但您可以按照專案 README 中的說明,透過幾個簡單步驟切換到 Prisma Postgres。


與 Prisma 保持聯繫

透過以下方式與我們聯繫,繼續您的 Prisma 旅程: 我們的活躍社群。保持資訊靈通、參與其中,並與其他開發者合作

我們衷心感謝您的參與,並期待您成為我們社群的一份子!

© . This site is unofficial and not affiliated with Prisma Data, Inc.