跳到主要內容

使用 JavaScript 和 CockroachDB 查詢資料庫

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

生成 Prisma Client 後,你就可以開始編寫查詢來讀寫資料庫中的資料了。本指南將使用一個簡單的 Node.js 指令碼來探索 Prisma Client 的一些基本功能。

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

index.js
const { PrismaClient } = require('./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/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 表添加了新記錄

使用者

id電子郵件名稱
1"alice@prisma.io""Alice"

帖子

id建立時間更新時間標題內容已釋出作者ID
12020-03-21T16:45:01.246Z2020-03-21T16:45:01.246Z"Hello World"nullfalse1

個人資料

id簡介使用者ID
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 記錄現在已在資料庫中更新

帖子

id標題內容已釋出作者ID
1"Hello World"nulltrue1

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

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