prisma学习

1. 安装

  npm install prisma -g

2. 创建项目

  prisma init -h  // 查看命令

  prisma init --datasource-provider mysql  // 创建项目

3. 环境配置  

 4. 表结构

 5. 生成表

  prisma migrate dev

6. 其他

  tsc --init 生成ts配置 文件  // 可能需要提前安装 npm i typescript -g

  npm i ts-node -g

  npm i express 

  创建一个.ts文件 启动该ts 文件即启动服务

import express from 'express'
import { PrismaClient } from '../generated/prisma'

const prisma = new PrismaClient()

const app = express()

const port = 3000

// 支持一下json
app.use(express.json())

app.post('/create', async (req, res) => {
    const {name,email} = req.body
    const data = await prisma.user.create({
        data: {
            name,
            email,
            posts: {
                create: [
                    {
                        title: "文章1",
                        content: "内容1"
                    },
                    {
                        title: "文章2",
                        content: "内容2"
                    }
                ]
            }
        }
    })
    res.send(data)
})

// 编辑
app.post('/update', async (req,res) => {
    const { name, email, id } = req.body
    const data = await prisma.user.update({
        data: {
            name,
            email
        },
        where: {
            id: Number(id)
        }
    })     
    res.send(data)
})

// 查询
app.get('/', async (req,res) => {
    const data = await prisma.user.findMany({
        include: {
            posts: true
        }
    })
    res.send(data)
})

// 单个查询
app.get('/user/:id', async (req,res) => {
    const row = await prisma.user.findMany({
        include: {
            posts: true
        },
        where: {
            id: Number(req.params.id)
        }
    })

    res.send(row)
})

// 删除

app.delete('/delete', async (req,res) => {
    // 级联删除 先把该用户下的文章删除
    
    await prisma.post.deleteMany({
        where: {
            authorId: Number(req.body.id)
        }
    })
    const data = await prisma.user.delete({
        where: {
            id: Number(req.body.id)
        }
    })
    res.send(data)
})

app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`)
})

 

posted on 2025-07-03 23:18  贲风  阅读(31)  评论(0)    收藏  举报