跳到主要内容

全栈

诸如 Next.js、Remix 或 SvelteKit 等全栈框架模糊了服务器和客户端之间的界限。这些框架还提供了不同的模式来在服务器上获取和修改数据。

您可以使用您选择的框架,从应用程序的服务器端部分,通过 Prisma Client 查询您的数据库。

支持的框架

以下是可与 Prisma ORM 一起使用的框架和库的不完全列表

全栈应用示例(例如 Next.js)

提示

如果您想学习如何使用 Next.js 和 Prisma ORM 构建应用,请查看这个全面的 视频教程

假设您有一个类似于这样的 Prisma schema

datasource db {
provider = "sqlite"
url = "file:./dev.db"
}

generator client {
provider = "prisma-client-js"
}

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

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

现在,您可以在 getServerSidePropsgetStaticProps、API 路由中,或者使用 API 库(例如 tRPCGraphQL),使用 Prisma Client API 实现查询数据库的逻辑。

getServerSideProps

// (in /pages/index.tsx)

// Alternatively, you can use `getStaticProps`
// in place of `getServerSideProps`.
export const getServerSideProps = async () => {
const feed = await prisma.post.findMany({
where: {
published: true,
},
})
return { props: { feed } }
}

Next.js 会将 props 传递给您的 React 组件,您可以在其中显示来自数据库的数据。

API 路由

// Fetch all posts (in /pages/api/posts.ts)
const prisma = new PrismaClient()

export default async function handle(req, res) {
const posts = await prisma.post.findMany({
where: {
published: true,
},
})
res.json(posts)
}

请注意,您可以在 Next.js API 路由中使用 Prisma ORM 向数据库发送查询——通过 REST、GraphQL 和 tRPC。

然后,您可以获取数据并将其显示在前端。

即用型全栈示例项目

您可以在 prisma-examples 仓库中找到几个展示如何使用 Prisma Client 构建全栈应用的即用型示例。

示例描述
Next.js全栈 Next.js 15 应用
Next.js (GraphQL)使用 GraphQL Yoga、Pothos 和 Apollo Client 的全栈 Next.js 应用
Remix使用 actions 和 loaders 的全栈 Remix 应用
SvelteKit使用 actions 和 loaders 的全栈 Sveltekit 应用
Nuxt使用 API 路由的全栈 Nuxt 应用