查詢資料庫
使用 Prisma Client 撰寫您的第一個查詢
現在您已經產生了 Prisma Client,您可以開始撰寫查詢來讀取和寫入資料庫中的資料。
如果您正在建構 REST API,您可以在您的路由處理器中使用 Prisma Client,根據傳入的 HTTP 請求來讀取和寫入資料庫中的資料。如果您正在建構 GraphQL API,您可以在您的解析器中使用 Prisma Client,根據傳入的查詢和變更來讀取和寫入資料庫中的資料。
然而,為了本指南的目的,您將只建立一個純 Node.js 腳本,以學習如何使用 Prisma Client 向資料庫發送查詢。一旦您了解 API 的運作方式,您就可以開始將其整合到您的實際應用程式碼中(例如 REST 路由處理器或 GraphQL 解析器)。
建立一個名為 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)
})
以下是程式碼片段不同部分的快速概覽
- 從 `@prisma/client` node 模組匯入
PrismaClient
建構子 - 實例化
PrismaClient
- 定義一個名為
main
的async
函數,以向資料庫發送查詢 - 呼叫
main
函數 - 當腳本終止時,關閉資料庫連線
根據您的模型外觀,Prisma Client API 也會有所不同。例如,如果您有一個 User
模型,您的 PrismaClient
實例會公開一個名為 user
的屬性,您可以在其上呼叫 CRUD 方法,例如 `findMany`、`create` 或 `update`。該屬性以模型命名,但第一個字母是小寫的(因此對於 Post
模型,它被稱為 `post`,對於 Profile
模型,它被稱為 `profile`)。
以下範例均基於 Prisma schema 中的模型。
在 main
函數內部,新增以下查詢以從資料庫讀取所有 User
記錄並印出結果
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
現在使用您目前的 TypeScript 設定執行程式碼。如果您使用 tsx
,您可以這樣執行它
npx tsx index.ts
如果您使用資料庫內省步驟中的 schema 建立資料庫,則查詢應印出一個空陣列,因為資料庫中尚無 `User` 記錄。
[]
如果您內省了一個具有記錄的現有資料庫,則查詢應傳回一個 JavaScript 物件陣列。
將資料寫入資料庫
您在前一節中使用的 findMany
查詢僅從資料庫 *讀取* 資料。在本節中,您將學習如何撰寫查詢,以將新記錄 *寫入* `Post` 和 `User` 表格中。
調整 main
函數以向資料庫發送 `create` 查詢
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
記錄,以及新的 `Post` 和 `Profile` 記錄。`User` 記錄分別透過 `Post.author` ↔ `User.posts` 和 `Profile.user` ↔ `User.profile` 關聯欄位連接到其他兩個記錄。
請注意,您正在將 `include` 選項傳遞給 `findMany`,這會告訴 Prisma Client 在傳回的 `User` 物件上包含 `posts` 和 `profile` 關聯。
使用您目前的 TypeScript 設定執行程式碼。如果您使用 tsx
,您可以這樣執行它
npx tsx index.ts
在繼續下一節之前,您將使用 `update` 查詢「發布」您剛建立的 `Post` 記錄。如下調整 `main` 函數
async function main() {
const post = await prisma.post.update({
where: { title: 'Hello World' },
data: { published: true },
})
console.log(post)
}
使用您目前的 TypeScript 設定執行程式碼。如果您使用 tsx
,您可以這樣執行它
npx tsx index.ts