跳到主內容

從 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 檔案。
  • 已在 .env 檔案中設定 DATABASE_URL 環境變數。

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 --save-dev

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

接下來,使用專案中的 tsconfig.json 檔案初始化 TypeScript

npx tsc --init

2.2. 設定 Prisma ORM

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

npm install prisma --save-dev
npm install @prisma/extension-accelerate

2.3. 建立一個 TypeScript 指令碼

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

touch index.ts

3. 遷移資料庫模式

更新您的 prisma/schema.prisma 檔案以包含一個簡單的 User 模型

prisma/schema.prisma
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

4. 使用 Prisma ORM 傳送查詢

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

index.ts
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

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.1. 建立新的 User 記錄

讓我們從一個小的查詢開始,在資料庫中建立一個新的 User 記錄並將結果物件記錄到控制檯。將以下程式碼新增到您的 index.ts 檔案中

index.ts
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

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.2. 檢索所有 User 記錄

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

刪除之前的 Prisma ORM 查詢,並新增新的 findMany 查詢

index.ts
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

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.3. 探索關聯查詢

Prisma ORM 的主要特點之一是易於處理關聯。在本節中,您將學習如何在巢狀寫入查詢中建立 UserPost 記錄。之後,您將瞭解如何使用 include 選項從資料庫中檢索關聯。

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

index.ts
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

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 { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

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

使用 Prisma Postgres,您還可以直接在透過在您的專案中選擇 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.