跳到主要内容

查询数据库

使用 Prisma Client 编写你的第一个查询

生成 Prisma Client 后,你就可以开始编写查询来读取和写入数据库中的数据了。

如果你正在构建 REST API,可以在路由处理程序中使用 Prisma Client 根据传入的 HTTP 请求读取和写入数据库中的数据。如果你正在构建 GraphQL API,可以在解析器中使用 Prisma Client 根据传入的查询和变更读取和写入数据库中的数据。

然而,在本指南中,你将创建一个简单的 Node.js 脚本,学习如何使用 Prisma Client 向数据库发送查询。一旦了解了 API 的工作原理,就可以开始将其集成到实际的应用程序代码中(例如 REST 路由处理程序或 GraphQL 解析器)。

创建一个名为 index.ts 的新文件,并添加以下代码:

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)
})

以下是代码片段各部分的快速概述:

  1. @prisma/client Node 模块导入 PrismaClient 构造函数
  2. 实例化 PrismaClient
  3. 定义一个名为 mainasync 函数,用于向数据库发送查询
  4. 调用 main 函数
  5. 脚本终止时关闭数据库连接

根据你的模型的外观,Prisma Client API 也会有所不同。例如,如果你有一个 User 模型,你的 PrismaClient 实例会暴露一个名为 user 的属性,你可以在其上调用 CRUD 方法,如 findManycreateupdate。该属性以模型命名,但首字母小写(因此对于 Post 模型,它称为 post;对于 Profile 模型,它称为 profile)。

以下示例都基于 Prisma schema 中的模型。

main 函数内部,添加以下查询来读取数据库中的所有 User 记录并打印结果:

index.ts
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}

现在使用当前的 TypeScript 环境运行代码。如果你正在使用 tsx,可以这样运行:

npx tsx index.ts

如果你使用数据库内省步骤中的 schema 创建了数据库,该查询应该打印一个空数组,因为数据库中还没有 User 记录。

[]

如果你内省了包含记录的现有数据库,该查询应该返回一个 JavaScript 对象数组。

向数据库写入数据

上一节使用的 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 关联。

使用当前的 TypeScript 环境运行代码。如果你正在使用 tsx,可以这样运行:

npx tsx index.ts

在继续到下一节之前,你将使用 update 查询“发布”刚刚创建的 Post 记录。请按如下方式调整 main 函数:

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

使用当前的 TypeScript 环境运行代码。如果你正在使用 tsx,可以这样运行:

npx tsx index.ts