跳到主內容

使用 TypeScript 和 Prisma ORM 查詢您現有的 PlanetScale 資料庫

使用 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

如果您使用資料庫內省步驟中的模式建立了資料庫,則查詢應該列印一個空陣列,因為資料庫中還沒有 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
© . This site is unofficial and not affiliated with Prisma Data, Inc.