Skip to main content

从 CLI

此页面提供了使用 prisma init --db 设置 Prisma Postgres 后的分步指南:

¥This page provides a step-by-step guide for Prisma Postgres after setting it up with prisma init --db:

  1. 使用 Prisma ORM 设置 TypeScript 应用

    ¥Set up a TypeScript app with Prisma ORM

  2. 迁移数据库的架构

    ¥Migrate the schema of your database

  3. 从 TypeScript 查询你的数据库

    ¥Query your database from TypeScript

先决条件

¥Prerequisites

本指南假设你使用 prisma init --db 设置了 Prisma Postgres 实例:

¥This guide assumes you set up Prisma Postgres instance with prisma init --db:

npx prisma@latest init --db
Show CLI results

此命令终止后:

¥Once this command terminated:

  • 你已登录 Prisma 数据平台。

    ¥You're logged into Prisma Data Platform.

  • 已创建一个新的 Prisma Postgres 实例。

    ¥A new Prisma Postgres instance was created.

  • prisma/ 文件夹是使用空的 schema.prisma 文件创建的。

    ¥The prisma/ folder was created with an empty schema.prisma file.

  • DATABASE_URL 环境变量是在 .env 文件中设置的。

    ¥The DATABASE_URL env var was set in a .env file.

1. 组织项目目录

¥ Organize your project directory

注意

如果你在希望项目所在的文件夹中运行 prisma init --db 命令,则可以跳过此步骤和 继续下一步部分

¥If you ran the prisma init --db command inside a folder where you want your project to live, you can skip this step and proceed to the next section.

如果你在预期的项目目录之外运行该命令(例如,在你的主文件夹或其他位置),则需要将生成的 prisma 文件夹和 .env 文件移动到专用的项目目录中。

¥If you ran the command outside your intended project directory (e.g., in your home folder or another location), you need to move the generated prisma folder and the .env file into a dedicated project directory.

创建一个新的文件夹(例如 hello-prisma),你希望你的项目驻留在该文件夹中,并将必要的文件移入其中:

¥Create a new folder (e.g. hello-prisma) where you want your project to live and move the necessary files into it:

mkdir hello-prisma
mv .env ./hello-prisma/
mv prisma ./hello-prisma/

导航到你的项目文件夹:

¥Navigate into your project folder:

cd ./hello-prisma

现在你的项目位于正确的位置,请继续设置。

¥Now that your project is in the correct location, continue with the setup.

2. 设置你的项目

¥ Set up your project

2.1.设置 TypeScript

¥2.1. Set up TypeScript

初始化 TypeScript 项目并将 Prisma CLI 添加为开发依赖:

¥Initialize a TypeScript project and add the Prisma CLI as a development dependency:

npm init -y
npm install typescript tsx @types/node --save-dev

这将为你的 TypeScript 应用创建一个带有初始设置的 package.json 文件。

¥This creates a package.json file with an initial setup for your TypeScript app.

接下来,在项目中使用 tsconfig.json 文件初始化 TypeScript:

¥Next, initialize TypeScript with a tsconfig.json file in the project:

npx tsc --init

2.2.设置 Prisma ORM

¥2.2. Set up Prisma ORM

安装使用 Prisma Postgres 所需的依赖:

¥Install the required dependencies to use Prisma Postgres:

npm install prisma --save-dev
npm install @prisma/extension-accelerate

2.3.创建 TypeScript 脚本

¥2.3. Create a TypeScript script

在根目录中创建一个 index.ts 文件,这将用于使用 Prisma ORM 查询你的应用:

¥Create an index.ts file in the root directory, this will be used to query your application with Prisma ORM:

touch index.ts

3. 迁移数据库模式

¥ Migrate the database schema

更新你的 prisma/schema.prisma 文件以包含一个简单的 User 模型:

¥Update your prisma/schema.prisma file to include a simple User model:

prisma/schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}

model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}

添加模型后,使用 Prisma 迁移 迁移数据库:

¥After adding the models, migrate your database using Prisma Migrate:

npx prisma migrate dev --name init

4. 使用 Prisma ORM 发送查询

¥ Send queries with Prisma ORM

将以下样板粘贴到 index.ts 中:

¥Paste the following boilerplate into index.ts:

index.ts
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

async function main() {
// ... you will write your Prisma ORM queries here
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

此代码包含在脚本末尾调用的 main 函数。它还会实例化 PrismaClient,你将使用它向数据库发送查询。

¥This code contains a main function that's invoked at the end of the script. It also instantiates PrismaClient which you'll use to send queries to your database.

4.1.创建新的 User 记录

¥4.1. Create a new User record

让我们从一个小查询开始,在数据库中创建一个新的 User 记录并将结果对象记录到控制台。将以下代码添加到你的 index.ts 文件中:

¥Let's start with a small query to create a new User record in the database and log the resulting object to the console. Add the following code to your index.ts file:

index.ts
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

async function main() {
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
},
})
console.log(user)
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

接下来,使用以下命令执行脚本:

¥Next, execute the script with the following command:

npx tsx index.ts
Show CLI results
{ id: 1, email: 'alice@prisma.io', name: 'Alice' }

干得好,你刚刚使用 Prisma Postgres 创建了第一个数据库记录!🎉

¥Great job, you just created your first database record with Prisma Postgres! 🎉

4.2.检索所有 User 条记录

¥4.2. Retrieve all User records

Prisma ORM 提供各种查询来从你的数据库中读取数据。在本部分中,你将使用 findMany 查询返回数据库中给定模型的所有记录。

¥Prisma ORM offers various queries to read data from your database. In this section, you'll use the findMany query that returns all the records in the database for a given model.

删除之前的 Prisma ORM 查询并添加新的 findMany 查询:

¥Delete the previous Prisma ORM query and add the new findMany query instead:

index.ts
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

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

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

再次执行脚本:

¥Execute the script again:

npx tsx index.ts
Show CLI results
[{ id: 1, email: 'alice@prisma.io', name: 'Alice' }]

请注意,单个 User 对象现在如何在控制台中用方括号括起来。这是因为 findMany 返回了一个数组,里面有一个对象。

¥Notice how the single User object is now enclosed with square brackets in the console. That's because the findMany returned an array with a single object inside.

4.3.探索关系查询

¥4.3. Explore relation queries

Prisma ORM 的主要功能之一是易于使用 relations。在本部分中,你将了解如何在嵌套写入查询中创建 UserPost 记录。然后,你将看到如何使用 include 选项从数据库中检索关系。

¥One of the main features of Prisma ORM is the ease of working with relations. In this section, you'll learn how to create a User and a Post record in a nested write query. Afterwards, you'll see how you can retrieve the relation from the database using the include option.

首先,调整脚本以包含嵌套查询:

¥First, adjust your script to include the nested query:

index.ts
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

async function main() {
const user = await prisma.user.create({
data: {
name: 'Bob',
email: 'bob@prisma.io',
posts: {
create: [
{
title: 'Hello World',
published: true
},
{
title: 'My second post',
content: 'This is still a draft'
}
],
},
},
})
console.log(user)
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

通过再次执行脚本来运行查询:

¥Run the query by executing the script again:

npx tsx index.ts
Show CLI results
{ id: 2, email: 'bob@prisma.io', name: 'Bob' }

为了还检索属于 UserPost 记录,你可以通过 posts 关系字段使用 include 选项:

¥In order to also retrieve the Post records that belong to a User, you can use the include option via the posts relation field:

index.ts
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'

const prisma = new PrismaClient().$extends(withAccelerate())

async function main() {
const usersWithPosts = await prisma.user.findMany({
include: {
posts: true,
},
})
console.dir(usersWithPosts, { depth: null })
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

再次运行脚本以查看嵌套读取查询的结果:

¥Run the script again to see the results of the nested read query:

npx tsx index.ts
Show CLI results
[
{ id: 1, email: 'alice@prisma.io', name: 'Alice', posts: [] },
{
id: 2,
email: 'bob@prisma.io',
name: 'Bob',
posts: [
{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 2
},
{
id: 2,
title: 'My second post',
content: 'This is still a draft',
published: false,
authorId: 2
}
]
}
]

这次,你将看到两个 User 对象被打印。它们都有一个 posts 字段(对于 "Alice" 为空,对于 "Bob" 填充了两个 Post 对象),代表与它们关联的 Post 记录。

¥This time, you're seeing two User objects being printed. Both of them have a posts field (which is empty for "Alice" and populated with two Post objects for "Bob") that represents the Post records associated with them.

下一步

¥Next steps

你刚刚熟悉了基本的 Prisma Postgres 设置。如果你想探索更复杂的查询,例如添加缓存功能,请查看官方 快速开始

¥You just got your feet wet with a basic Prisma Postgres setup. If you want to explore more complex queries, such as adding caching functionality, check out the official Quickstart.

在 Prisma Studio 中查看和编辑数据

¥View and edit data in Prisma Studio

Prisma ORM 附带一个内置 GUI,用于查看和编辑数据库中的数据。你可以使用以下命令打开它:

¥Prisma ORM comes with a built-in GUI to view and edit the data in your database. You can open it using the following command:

npx prisma studio

使用 Prisma Postgres,你还可以通过选择项目中的 Studio 选项卡直接在 中使用 Prisma Studio。

¥With Prisma Postgres, you can also directly use Prisma Studio inside the by selecting the Studio tab in your project.

使用 Next.js 构建全栈应用

¥Build a fullstack app with Next.js

了解如何在全栈应用中使用 Prisma Postgres:

¥Learn how to use Prisma Postgres in a fullstack app:

探索可立即运行的示例

¥Explore ready-to-run examples

查看 GitHub 上的 prisma-examples 存储库,了解如何将 Prisma ORM 与你喜欢的库一起使用。该存储库包含 Express、NestJS、GraphQL 的示例以及 Next.js 和 Vue.js 的全栈示例等等。

¥Check out the prisma-examples repository on GitHub to see how Prisma ORM can be used with your favorite library. The repo contains examples with Express, NestJS, GraphQL as well as fullstack examples with Next.js and Vue.js, and a lot more.

这些示例默认使用 SQLite,但你可以按照项目 README 中的说明,通过几个简单的步骤切换到 Prisma Postgres。

¥These examples use SQLite by default but you can follow the instructions in the project README to switch to Prisma Postgres in a few simple steps.


Stay connected with Prisma

Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:

We genuinely value your involvement and look forward to having you as part of our community!