跳到主要內容

查詢資料庫

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

現在您已產生 Prisma Client,您可以開始撰寫查詢來讀取和寫入資料庫中的資料。在本指南中,您將使用純 Node.js 腳本來探索 Prisma Client 的一些基本功能。

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

index.js
const { PrismaClient } = require('@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. 在腳本終止時關閉資料庫連線

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

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

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

node index.js

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

[]

將資料寫入資料庫

您在前一節中使用的 findMany 查詢僅讀取資料庫中的資料(即使它仍然是空的)。在本節中,您將學習如何撰寫查詢,將新記錄寫入 PostUser 表格中。

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

index.js
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 關聯。

使用此命令執行程式碼

node index.js

輸出應如下所示

[
{
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,
}
}
]

查詢將新記錄新增至 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 欄位,這表示 id1 欄位因此參考資料庫中的第一個(也是唯一一個)User 記錄。

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

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

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

node index.js

您將看到以下輸出

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

id1Post 記錄現在已在資料庫中更新

Post

idtitlecontentpublishedauthorId
1"Hello World"nulltrue1

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