全栈
全栈框架,如 Next.js、Remix 或 SvelteKit,模糊了服务器和客户端之间的界限。这些框架还提供了在服务器上获取和修改数据的不同模式。
您可以使用 Prisma Client,从应用程序的服务器端部分,使用您选择的框架来查询数据库。
支持的框架
以下是您可以使用 Prisma ORM 的框架和库的非详尽列表
全栈应用示例(例如 Next.js)
提示
如果您想学习如何使用 Next.js 和 Prisma ORM 构建应用程序,请查看这个全面的视频教程。
假设您有一个类似于这样的 Prisma 模式
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
generator client {
provider = "prisma-client"
output = "./generated"
}
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[]
}
您现在可以在 getServerSideProps、getStaticProps、API 路由中,或使用 API 库(如tRPC 和GraphQL)实现使用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 应用程序 |