跳到主要內容

使用 TypeScript 和 PostgreSQL 查詢資料庫

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

現在您已經生成了 Prisma Client,您可以開始編寫查詢來讀取和寫入資料庫中的資料。在本指南中,您將使用一個簡單的 Node.js 指令碼來探索 Prisma Client 的一些基本功能。

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

index.ts
import { PrismaClient } from './generated/prisma'

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 init 命令指定的輸出資料夾中匯入 PrismaClient。
  2. 例項化 PrismaClient
  3. 定義一個名為 main 的非同步函式,用於向資料庫傳送查詢
  4. 呼叫 main 函式
  5. 在指令碼終止時關閉資料庫連線

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

index.ts
async function main() {
// ... you will write your Prisma Client queries here
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}

現在使用此命令執行程式碼

npx tsx index.ts

這將列印一個空陣列,因為資料庫中還沒有 User 記錄

[]

向資料庫寫入資料

您在上一節中使用的 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 關係。

使用此命令執行程式碼

npx tsx index.ts

輸出應類似於此

[
{
email: 'alice@prisma.io',
id: 1,
name: 'Alice',
posts: [
{
content: null,
createdAt: 2020-03-21T16:45:01.246Z,
updatedAt: 2020-03-21T16:45:01.246Z,
id: 1,
published: false,
title: 'Hello World',
authorId: 1,
}
],
profile: {
bio: 'I like turtles',
id: 1,
userId: 1,
}
}
]

另請注意,allUsers 是靜態型別的,這得益於 Prisma Client 生成的型別。您可以透過將滑鼠懸停在編輯器中的 allUsers 變數上來觀察其型別。它應按如下方式鍵入:

const allUsers: (User & {
posts: Post[]
})[]

export type Post = {
id: number
title: string
content: string | null
published: boolean
authorId: number | null
}

該查詢已向 UserPost 表添加了新記錄

User

idemailname
1"alice@prisma.io""Alice"

Post

idcreatedAtupdatedAttitlecontentpublishedauthorId
12020-03-21T16:45:01.246Z2020-03-21T16:45:01.246Z"Hello World"nullfalse1

Profile

idbiouserId
1"I like turtles"1

注意Post 表中的 authorId 列和 Profile 表中的 userId 列中的數字都引用 User 表的 id 列,這意味著 id 值為 1 的列因此指的是資料庫中第一個(也是唯一一個)User 記錄。

在進入下一節之前,您將使用 update 查詢“釋出”您剛剛建立的 Post 記錄。請按如下方式調整 main 函式:

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

現在使用與之前相同的命令執行程式碼

npx tsx index.ts

您將看到以下輸出

{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 1
}

id 為 1Post 記錄現在已在資料庫中更新

Post

idtitlecontentpublishedauthorId
1"Hello World"nulltrue1

太棒了,您剛剛首次使用 Prisma Client 將新資料寫入了資料庫 🚀

© . This site is unofficial and not affiliated with Prisma Data, Inc.