使用 TypeScript 和 Prisma ORM 查詢您現有的 CockroachDB 資料庫
使用 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/clientnode 模組匯入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