跳到主要內容

查詢資料庫

使用 Prisma Client 撰寫您的第一個查詢

現在您已產生 Prisma Client,您可以開始撰寫查詢,以讀取和寫入資料庫中的資料。

如果您正在建構 REST API,您可以在路由處理程序中使用 Prisma Client,根據傳入的 HTTP 請求來讀取和寫入資料庫中的資料。如果您正在建構 GraphQL API,您可以在解析器中使用 Prisma Client,根據傳入的查詢和變更來讀取和寫入資料庫中的資料。

然而,為了本指南的目的,您將僅建立一個純 Node.js 腳本,以學習如何使用 Prisma Client 將查詢傳送到您的資料庫。一旦您了解 API 的運作方式,就可以開始將其整合到您的實際應用程式碼中(例如 REST 路由處理程序或 GraphQL 解析器)。

建立一個名為 index.ts 的新檔案,並將以下程式碼新增至其中

index.ts
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

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

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

以下是程式碼片段不同部分的快速概觀

  1. @prisma/client node 模組導入 PrismaClient 建構子
  2. 實例化 PrismaClient
  3. 定義一個名為 mainasync 函數,以將查詢傳送到資料庫
  4. 呼叫 main 函數
  5. 當腳本終止時,關閉資料庫連線

根據您的模型外觀,Prisma Client API 也會有所不同。例如,如果您有一個 User 模型,您的 PrismaClient 實例會公開一個名為 user 的屬性,您可以在其上呼叫 CRUD 方法,例如 findManycreateupdate。該屬性以模型命名,但第一個字母是小寫(因此對於 Post 模型,它稱為 post,對於 Profile 模型,它稱為 profile)。

以下範例均基於 Prisma schema 中的模型。

main 函數內部,新增以下查詢以從資料庫讀取所有 User 記錄並印出結果

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

現在使用您目前的 TypeScript 設定執行程式碼。如果您使用 tsx,您可以像這樣執行它

npx tsx index.ts

如果您使用從資料庫內省步驟中的 schema 建立資料庫,則查詢應印出一個空陣列,因為資料庫中尚無 User 記錄。

[]

如果您內省了具有記錄的現有資料庫,則查詢應傳回 JavaScript 物件的陣列。

將資料寫入資料庫

您在前一節中使用的 findMany 查詢僅讀取資料庫中的資料。在本節中,您將學習如何撰寫查詢,以將新記錄寫入PostUser 表格中。

調整 main 函數以將 create 查詢傳送到資料庫

index.ts
async function main() {
await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World' },
},
profile: {
create: { bio: 'I like turtles' },
},
},
})

const allUsers = await prisma.user.findMany({
include: {
posts: true,
profile: true,
},
})
console.dir(allUsers, { depth: null })
}

此程式碼使用巢狀寫入查詢建立新的 User 記錄,以及新的 PostProfile 記錄。User 記錄透過 Post.authorUser.postsProfile.userUser.profile 關聯欄位 分別連接到其他兩個記錄。

請注意,您正在將 include 選項傳遞給 findMany,這會告知 Prisma Client 在傳回的 User 物件上包含 postsprofile 關聯。

使用您目前的 TypeScript 設定執行程式碼。如果您使用 tsx,您可以像這樣執行它

npx tsx index.ts

在繼續下一節之前,您將使用 update 查詢「發布」您剛建立的 Post 記錄。如下調整 main 函數

index.ts
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}

使用您目前的 TypeScript 設定執行程式碼。如果您使用 tsx,您可以像這樣執行它

npx tsx index.ts