Prisma ORM 入门指南:从零开始的全栈技能学习之旅

📝 Prisma ORM 入门指南:从零开始的全栈技能学习之旅


一、🚀 概述 (Overview)

  • 引言与学习动机:

    • 这篇文章的目的是为了记录和分享学习 Prisma ORM 的入门过程。
    • 核心原因: 掌握一个全栈开发的新技能,以便能更高效、现代地进行后端和数据库开发。
  • 技术栈介绍:

    • 本次实战项目使用的主要技术栈:

      • 后端框架: Koa.js (轻量级 Node.js 框架)
      • ORM 技术: Prisma (现代数据库工具包)
    • 文章侧重点: 虽然使用了 Koa.js,但本文的重点 是帮助读者快速入门和理解 Prisma 的核心概念和用法


二、🛠️ 实战演练:Prisma 快速上手 (Hands-on Practice)

本章节将结合您的实际工程代码和命令,一步步引导读者。

2.1. 环境准备与项目初始化

  • 项目初始化命令:

    • npm init -y

    • npm install koa (安装 Koa)

    • 重点: 安装 Prisma 客户端和开发依赖:

      • npm install @prisma/client
      • npm install -D prisma (作为开发依赖安装 CLI)
  • Prisma 初始化:

    • 运行命令:npx prisma init

    • 说明该命令生成的文件:

      • prisma/schema.prisma (数据库模型定义文件)
      • .env (环境变量文件,用于存放数据库连接字符串)
ini 复制代码
DATABASE_URL="mysql://USER:PASSWORD@localhost:3306/DATABASE_NAME"  
  • 生成客户端
    • 运行命令:pnpm prisma generate

2.2. 定义数据模型 (Schema Definition)

kotlin 复制代码
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model User {
  id          Int      @id @default(autoincrement())
  name        String   
  email       String   @unique
  password    String
  createdTime DateTime @default(now()) @map("created_time")
  updatedTime DateTime @updatedAt @map("updated_time")
  @@map("user")
}

2.3. 数据库表新建

执行如下命令,实体就能推送到数据库中。

perl 复制代码
npx prisma db push

2.4 使用prisma进行增删改查

ini 复制代码
// ...existing code...
const Koa = require('koa')
const Router = require('@koa/router')
const bodyParser = require('koa-bodyparser')
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()

const app = new Koa()

// 实例化路由器,并设置公共路由前缀 /users
const router = new Router({
  prefix: '/users'
})

app.use(bodyParser())

// 查询用户列表
router.get('/', async ctx => {
  const users = await prisma.user.findMany()
  ctx.body = users
})

// 查询单个用户
router.get('/:id', async ctx => {
  const id = parseInt(ctx.params.id)
  const user = await prisma.user.findUnique({
    where: { id }
  })
  ctx.body = user
})

// 创建用户
router.post('/', async ctx => {
  const user = ctx.request.body
  const newUser = await prisma.user.create({
    data: user
  })
  ctx.body = newUser
})

// 更新用户
router.patch('/:id', async ctx => {
  const id = parseInt(ctx.params.id)
  const updateUser = ctx.request.body
  const user = await prisma.user.update({
    where: {
      id
    },
    data: updateUser
  })
  ctx.body = user
})

// 删除用户
router.delete('/:id', async ctx => {
  const id = parseInt(ctx.params.id)
  const user = await prisma.user.delete({
    where: {
      id
    }
  })
  ctx.body = user
})

// 注册路由中间件
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000, () => {
  console.log('服务器运行在 3000 端口')
})
// ...existing code...

三、💡 总结与思考 (Conclusion and Reflection)

  • 本次遇到的主要问题:

  • 未来学习方向(引出下一篇):

    • Koa:
    • Prisma更多功能点
相关推荐
FogLetter4 小时前
大文件上传?我用分片上传+断点续传彻底解决了!
前端·javascript
2501_938780284 小时前
《Node.js 面试考点精讲:Express 生态与常见问题解决方案》
面试·node.js·express
夕山雨4 小时前
Node.js 主流框架对比
node.js
2501_938790074 小时前
《Node.js 面试避坑:Express 常见问题误区与正确答案解析》
面试·node.js·express
涔溪4 小时前
使用Node.js连接 OPC UA Server
node.js·opcua
学习3人组4 小时前
Node.js模块化开发课堂案例
node.js
Qinana4 小时前
🌟ES6 字符串模板与数组 map 的优雅实践
前端·javascript·程序员
optimistic_chen4 小时前
【Java EE进阶 --- SpringBoot】统一功能处理(拦截器)
spring boot·后端·java-ee·log4j·拦截器
残冬醉离殇4 小时前
深入理解浏览器事件系统:从用户点击到事件对象的完整旅程
前端·javascript