使用 TypeScript 和 Prisma Postgres 查询数据库
使用 Prisma 客户端编写你的第一个查询
¥Write your first query with Prisma Client
现在你已经生成了 Prisma 客户端,你可以开始编写查询以在数据库中读取和写入数据。出于本指南的目的,你将使用纯 TypeScript 脚本来探索 Prisma Client 的一些基本功能。
¥Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain TypeScript script to explore some basic features of Prisma Client.
创建一个名为 queries.ts
的新文件并添加以下代码:
¥Create a new file named queries.ts
and add the following code to it:
// 1
import { PrismaClient } from './generated/prisma'
import { withAccelerate } from '@prisma/extension-accelerate'
// 2
const prisma = new PrismaClient()
.$extends(withAccelerate())
// 3
async function main() {
// ... you will write your Prisma Client queries here
}
// 4
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
// 5
await prisma.$disconnect()
process.exit(1)
})
以下是代码片段不同部分的快速概述:
¥Here's a quick overview of the different parts of the code snippet:
-
导入
PrismaClient
构造函数和withAccelerate
扩展。¥Import the
PrismaClient
constructor and thewithAccelerate
extension. -
实例化
PrismaClient
并添加 Accelerate 扩展。¥Instantiate
PrismaClient
and add the Accelerate extension. -
定义一个名为
main
的async
函数以向数据库发送查询。¥Define an
async
function namedmain
to send queries to the database. -
调用
main
函数。¥Call the
main
function. -
脚本终止时关闭数据库连接。
¥Close the database connections when the script terminates.
在 main
函数内,添加以下查询以从数据库中读取所有 User
记录并记录结果:
¥Inside the main
function, add the following query to read all User
records from the database and log the result:
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
现在使用以下命令运行代码:
¥Now run the code with this command:
npx tsx queries.ts
这应该打印一个空数组,因为数据库中还没有 User
记录:
¥This should print an empty array because there are no User
records in the database yet:
[]
将数据写入数据库
¥Write data into the database
你在上一节中使用的 findMany
查询仅从数据库中读取数据(尽管它仍然是空的)。
¥The findMany
query you used in the previous section only reads data from the database (although it was still empty).
在本节中,你将学习如何编写查询以将新记录同时写入 Post
、User
和 Profile
表中。
¥In this section, you'll learn how to write a query to write new records into the Post
, User
and Profile
tables all at once.
通过删除之前的代码并添加以下内容来调整 main
函数:
¥Adjust the main
function by removing the code from before and adding the following:
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
记录。
¥This code creates a new User
record together with new Post
and Profile
records using a nested write query.
记录通过你在 Prisma 模式中定义的 关系字段 连接。
¥The records are connected via the relation fields that you defined in your Prisma schema.
请注意,你还将 include
选项传递给 findMany
,这告诉 Prisma Client 在返回的 User
对象中包含 posts
和 profile
关系。
¥Notice that you're also passing the include
option to findMany
which tells Prisma Client to include the posts
and profile
relations on the returned User
objects.
使用以下命令运行代码:
¥Run the code with this command:
npx tsx queries.ts
输出应类似于以下内容:
¥The output should look similar to this:
[
{
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
变量上来观察类型。应输入如下:
¥Also note that the allUsers
variable is statically typed thanks to Prisma Client's generated types. You can observe the type by hovering over the allUsers
variable in your editor. It should be typed as follows:
const allUsers: ({
posts: {
id: number;
createdAt: Date;
updatedAt: Date;
title: string;
content: string | null;
published: boolean;
authorId: number;
}[];
profile: {
id: number;
bio: string | null;
userId: number;
} | null;
} & {
...;
})[]
Expand for a visual view of the records that have been created
查询向 User
、Post
和 Profile
表添加了新记录:
¥The query added new records to the User
, Post
, and Profile
tables:
用户
¥User
id | name | |
---|---|---|
1 | "alice@prisma.io" | "Alice" |
邮政
¥Post
id | createdAt | updatedAt | title | content | published | authorId |
---|---|---|---|---|---|---|
1 | 2020-03-21T16:45:01.246Z | 2020-03-21T16:45:01.246Z | "Hello World" | null | false | 1 |
轮廓
¥Profile
id | bio | userId |
---|---|---|
1 | "I like turtles" | 1 |
Post
上的 authorId
列和 Profile
上的 userId
列中的数字都引用 User
表的 id
列,这意味着 id
值 1
列因此引用数据库中的第一条(也是唯一一条)User
记录。
¥The numbers in the authorId
column on Post
and userId
column on Profile
both reference the id
column of the User
table, meaning the id
value 1
column therefore refers to the first (and only) User
record in the database.
在继续下一部分之前,你需要对刚刚使用 update
查询创建的 Post
记录进行 "publish" 操作。调整 main
功能如下:
¥Before moving on to the next section, you'll "publish" the Post
record you just created using an update
query. Adjust the main
function as follows:
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}
现在使用与之前相同的命令运行代码:
¥Now run the code using the same command as before:
npx tsx queries.ts
你将看到以下输出:
¥You will see the following output:
{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 1
}
id
为 1
的 Post
记录现已在数据库中更新:
¥The Post
record with an id
of 1
now got updated in the database:
邮政
¥Post
id | title | content | published | authorId |
---|---|---|---|---|
1 | "Hello World" | null | true | 1 |
恭喜!你现在已经了解了如何在应用中使用 Prisma Client 查询 Prisma Postgres 数据库。如果你在此过程中迷路了,想要了解更多查询或探索 Prisma Accelerate 的缓存功能,请查看全面的 Prisma 入门模板。
¥Congratulations! You've now learned how to query a Prisma Postgres database with Prisma Client in your application. If you got lost along the way, want to learn about more queries or explore the caching feature of Prisma Accelerate, check out the comprehensive Prisma starter template.