初实Prisma 使用教程

Prisma 使用教程

Prisma是一款现代化的数据库访问工具,它提供了一种便捷的方式来操作数据库,同时也提供了多种功能,包括数据模型定义、迁移、身份验证和授权等。下面我们将介绍如何使用Prisma来构建一个简单的Web应用程序。

Prisma 链接:

https://prisma.yoga/concepts/overview/why-prisma

安装Prisma

首先,你需要安装Prisma和相关的依赖项。可以使用npm或yarn来进行安装。在终端中输入以下命令即可完成安装。

npm install prisma --save
或
yarn add prisma

定义数据模型
接下来,需要定义数据模型。假设我们要构建一个简单的博客应用程序,我们需要定义博客、博客作者和评论三个数据模型。在项目根目录下创建一个prisma文件夹,在prisma文件夹下创建一个schema.prisma文件,定义数据模型。

model Blog {
id Int @id @default(autoincrement())
title String
content String
author User @relation(fields: [authorId], references: [id])
authorId Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
comments Comment[]
}

model User {
id Int @id @default(autoincrement())
name String
email String @unique
password String
blogs Blog[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Comment {
id Int @id @default(autoincrement())
content String
author User @relation(fields: [authorId], references: [id])
authorId Int
blog Blog @relation(fields: [blogId], references: [id])
blogId Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

生成数据库
接下来,我们需要使用Prisma生成数据库。在终端中输入以下命令。

npx prisma migrate dev --name init
或
yarn prisma migrate dev --name init

这将创建一个名为init的数据库迁移,并使用该迁移来生成数据库。

执行查询
现在,我们可以使用Prisma来执行查询。在项目中创建一个src文件夹,在文件夹下创建一个index.js文件。在index.js文件中,我们可以使用Prisma来执行查询。

const { PrismaClient } = require(“@prisma/client”);
const prisma = new PrismaClient();

async function main() {
const blogs = await prisma.blog.findMany({
include: {
author: true,
comments: true,
},
});
console.log(blogs);
}

main()
.catch((e) => {
throw e;
})
.finally(async () => {
await prisma.$disconnect();
});

在上面的代码中,我们使用Prisma来查询所有博客,并包含博客作者和评论。运行脚本,我们可以在控制台中看到查询结果。

总结
Prisma是一个非常强大的数据库访问工具,可以帮助我们快速构建高效的应用程序。通过定义数据模型和使用Prisma的API,我们可以轻松地执行数据库操作。希望这篇文章能够帮助你快速上手使用Prisma。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值