浅尝 express + ORM框架 prisma 的结合

一、prisma起步

安装:

npm i prisma -g

查看初始化帮助信息:

prisma init -h

查看初始化帮助信息结果:

Set up a new Prisma project

Usage

  $ prisma init [options]
Options

           -h, --help   Display this help message
--datasource-provider   Define the datasource provider to use: postgresql, mysql, sqlite, sqlserver, mongodb or cockroachdb
 --generator-provider   Define the generator provider to use. Default: `prisma-client-js`
    --preview-feature   Define a preview feature to use.
             --output   Define Prisma Client generator output path to use.
                --url   Define a custom datasource url

Examples

Set up a new Prisma project with PostgreSQL (default)
  $ prisma init

Set up a new Prisma project and specify MySQL as the datasource provider to use
  $ prisma init --datasource-provider mysql

Set up a new Prisma project and specify `prisma-client-go` as the generator provider to use
  $ prisma init --generator-provider prisma-client-go

Set up a new Prisma project and specify `x` and `y` as the preview features to use
  $ prisma init --preview-feature x --preview-feature y

Set up a new Prisma project and specify `./generated-client` as the output path to use
  $ prisma init --output ./generated-client

Set up a new Prisma project and specify the url that will be used
  $ prisma init --url mysql://user:password@localhost:3306/mydb

初始化:

#初始化项目,并指定采用的数据库类型为 xxxx 例子采用mysql
prisma init --datasource-provider mysql

初始化结果:


✔ Your Prisma schema was created at prisma/schema.prisma
  You can now open it in your favorite editor.

Next steps:
1. Set the DATABASE_URL in the .env file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started
2. Run prisma db pull to turn your database schema into a Prisma schema.
3. Run prisma generate to generate the Prisma Client. You can then start querying your database.

More information in our documentation:
https://pris.ly/d/getting-started

┌────────────────────────────────────────────────────────────────┐
│  Developing real-time features?                                │
│  Prisma Pulse lets you respond instantly to database changes.  │
│  https://pris.ly/cli/pulse                                     │
└────────────────────────────────────────────────────────────────┘

初始化生成目录:
在这里插入图片描述

二、配置数据库连接

.env文件中对数据库连接信息进行配置:

更多数据库连接方式查看文档

# MySql 数据库的连接方式
# DATABASE_URL="mysql://账号:密码@主机:端口/数据库名"
DATABASE_URL="mysql://root:1234aa@localhost:3306/mysqlorm"

三、编写表结构

表结构在/prisma/schema.prisma文件中编写

1. model 表 声明

1.1 简单声明一个表的例子:
model User{
  id        Int      @id @default(autoincrement()) // id int 类型 自增
  email     String   @unique // email  String 类型 唯一项
  name      String
  createdAt DateTime @default(now())
}
1.2 声明一对多表关联的例子
model User{
  id        Int      @id @default(autoincrement()) // id int 类型 自增
  email     String   @unique // email  String 类型 唯一项
  name      String
  posts      Post[] // 一对多的关系
}
model Post{
  id        Int      @id @default(autoincrement())
 title String 
 content String
 author     User #relation(fields:[authorId],references:[id]) // 关联User表中的id到authorId字段
 authorId Int 
}
1.3 创建具体的表结构到数据库中

执行该语句如果数据库已经存在询问是否覆盖。

prisma migrate dev

可能得报错为mkdir 权限,找不到package.json文件
npm init 一下创建package.json文件再执行就好了

四、编写express

  1. 新建src目录用来编写接口文件进行操作数据库
  2. 新建启动文件main.js
const express = require('express') // 引入express
const { PrismaClient } =  require( '@prisma/client')// 引入prisma

const prisma = new PrismaClient() // new 新建类实例
const app = express()  // 初始化express
const port = 3000 // 端口号

app.get('/test', async (req, res) => { // 启动测试服务
    try {
    // 类实例.表名.操作({ data:{filedName:filedValue})
        await prisma.user.create({ 
            data: {
                name:'嘻嘻',
                email:'xxx@ww.com',
                posts:{ // 同步创建关联的post表信息。 这里的 posts 在 三、编写表结构中的1.2节定义
                    create:[ // 操作 批量操作数组,单次操作数组内的单一对象即可 可继续嵌套
                        {  
                            title: 'My first post',
                            content: 'This is my first post'
                        },
                        {
                            title:'My 2nd post',
                            content:'This is my 2nd post '
                        }
                    ]
                }
            }
        })
    res.send('ok')

    } catch (error) {
        res.send(error)
    }
})


app.listen(port, () => {
    console.log(`http://lcoalhost:${port}`)
})

插入数据

简单插入数据
await prisma.user.create({ 
            data: {
                name:'嘻嘻',
                email:'xxx@ww.com'
               }
        })
复杂插入数据
// prisma 导入类new的实例 
// user 表名
// create 创建的操作
await prisma.user.create({ 
            data: {
                name:'嘻嘻',
                email:'xxx@ww.com',
                posts:{ // 同步创建关联的post表信息。 这里的 posts 在 三、编写表结构中的1.2节定义
                    create:[ // 操作 批量操作数组,单次操作数组内的单一对象即可 可继续嵌套
                        {  
                            title: 'My first post',
                            content: 'This is my first post'
                        },
                        {
                            title:'My 2nd post',
                            content:'This is my 2nd post '
                        }
                    ]
                }
            }
        })

查询数据

单表查询
// prisma 实例对象
// user 表名
// findMany 查找api
 const data = await prisma.user.findMany()
表关联查询
// prisma 实例对象
// user 表名
// findMany 查找api
// posts 关联 post表的字段
 const data = await prisma.user.findMany({
        include:{      
            posts:true
        }
    })
返回数据格式为树状
"data": [
        {
            "id": 1,
            "email": "fujsbah@sqq.com",
            "name": "xxxx",
            "posts": [
                {
                    "id": 1,
                    "title": "My first post",
                    "content": "This is my first post",
                    "authorId": 1
                },
                {
                    "id": 2,
                    "title": "My 2nd post",
                    "content": "This is my 2nd post ",
                    "authorId": 1
                }
            ]
        },
        {
            "id": 2,
            "email": "jsbah@sqq.com",
            "name": "xxxx",
            "posts": [
                {
                    "id": 3,
                    "title": "My first post",
                    "content": "This is my first post",
                    "authorId": 2
                },
                {
                    "id": 4,
                    "title": "My 2nd post",
                    "content": "This is my 2nd post ",
                    "authorId": 2
                }
            ]
        }
    ]
条件查询
app.get('/user/:id', async (req, res) => {
   try {
    const data = await prisma.user.findUnique({
        where:{
            id:Number(req.params.id) // 2
        },
        include:{
            posts:true
        }
    })
    res.send({
        code:'000000',
        msg:'success',
        data
    })
   } catch (error) {
    res.send({
        code:'000003',
        msg:'error',
        data:error
    })
   }
})
条件查询响应
{
    "code": "000000",
    "msg": "success",
    "data": {
        "id": 2,
        "email": "jsbah@sqq.com",
        "name": "xxxx",
        "posts": [
            {
                "id": 3,
                "title": "My first post",
                "content": "This is my first post",
                "authorId": 2
            },
            {
                "id": 4,
                "title": "My 2nd post",
                "content": "This is my 2nd post ",
                "authorId": 2
            }
        ]
    }
}

编辑数据

app.post('/update', upload.array(), async (req, res) => {
    const { name, id, email } = req.body
    try {
        let data = await prisma.user.update({
            data: {
                name,
                email
            },
            where: {
                id: Number(id)
            }
        })
        res.send({
            code: '000000',
            msg: 'success',
            data
        })

    } catch (error) {
        res.send({
            code: '000004',
            msg: 'error',
            data: error
        })
    }
})

删除数据

简单删除
app.post('/delete', upload.array(), async (req, res) => {
    const { id } = req.body
    try {
    // 删除post文章表中作者id等于传入的id的数据
        let deletePostData = await prisma.post.delete({
            where: {
                authorId: Number(id)
            }
        })
       
          
        res.send({
            code: '000000',
            msg: 'success',
            data:{
               deletePostData
            }
        })

    } catch (error) {
        res.send({
            code: '000005',
            msg: 'error',
            data: error
        })
    }
})

复合删除
app.post('/delete', upload.array(), async (req, res) => {
    const { id } = req.body
    // 目标删除用户
    try {
    // 先删除外键关联到用户id的文章表,这要是这个id的文章都删除
        let deletePostData = await prisma.post.delete({
            where: {
                authorId: Number(id)
            }
        })
        // 没有外键依赖到之后 根据id删除用户
        let deleteUserData =  await prisma.user.delete({
            where: {
                id: Number(id)
            }
        })
          
        res.send({
            code: '000000',
            msg: 'success',
            data:{
                deleteUserData,
                deletePostData
            }
        })

    } catch (error) {
        res.send({
            code: '000005',
            msg: 'error',
            data: error
        })
    }
})

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/548774.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Intewell-Hyper II_V2.1.1_工业实时操作系统软件版本发布

Intewell-Hyper II_V2.1.1_工业实时操作系统软件版本发布 Intewell-Hyper II_V2.1.1 版本号:V2.1.1 版本特点 新增V1.3.2分支上SHV构型合并及问题回归 版本或修改说明 增加功能: 1.V1.3.2分支上SHV构型合并及问题回归 2.适配NewPre3102和NewPre3101…

node+vue3的websocket前后端消息推送

nodevue3的websocket前后端消息推送 前期写web项目时,前端获取数据的方式一般是向后端发起数据请求,然后后端向前端发送数据,然后对数据进行渲染,这是最常规的一种数据通讯方式,适用于绝大部分前后端分离的项目 实际…

java的ConcurrentHashMap深入理解

概要 怎么保证线程安全: 在初始化数组时用了cas操作,sizectl作为占位标志(U.compareAndSwapInt(this, SIZECTL, sc, -1);获取数组中的元素是否已经有了,用Volatile修饰数组(保证可见性)&#…

边缘计算网关有哪些优势?-天拓四方

随着信息化、智能化浪潮的持续推进,计算技术正以前所未有的速度发展,而边缘计算网关作为其中的重要一环,以其独特的优势正在逐步改变我们的生活方式和工作模式。本文将详细解析边缘计算网关的优势。 首先,边缘计算网关具有显著的…

【好书推荐6】《Excel函数与公式应用大全for Excel 365 Excel 2021》

【好书推荐6】《Excel函数与公式应用大全for Excel 365 & Excel 2021》 写在最前面《Excel函数与公式应用大全for Excel 365 & Excel 2021》关键点内容简介作者简介前言/序言目录 🌈你好呀!我是 是Yu欸 🌌 2024每日百字篆刻时光&…

Linux之命令行参数的原理以及实现,环境变量限时增加删除和永久增加删除以及代码获取环境变量

个人主页:点我进入主页 专栏分类:C语言初阶 C语言进阶 数据结构初阶 Linux C初阶 算法 欢迎大家点赞,评论,收藏。 一起努力,一起奔赴大厂 一.命令行参数 1.1main函数参数 在我们学习c语言时我们的main函数…

Vue - 5( 16000 字 Vue2 入门级教程)

一:Vue 初阶 1.1 组件自定义事件 在 Vue 中,组件间通过自定义事件进行通信是一种常见的模式。自定义事件允许子组件向父组件发送消息,也可以在组件内部进行事件的绑定、触发和解绑。让我们详细讲解这些知识点。 1.1.1 组件自定义事件 在 …

最前沿・量子退火建模方法(2) : Domain wall encoding讲解和python实现

前言 上篇讲的subQUBO属于方法论,这次讲个通过编码量子比特的方式,同样的约束条件,不同的编码,所需的量子比特数是不同的。有的编码方式,很节省量子比特。比如,这次要讲的Domain wall encoding。 一、Doma…

一文总结:Python的封装、继承和多态

整个程序员的生涯,最重要的一个知识根基就是面向对象的理解和掌握深度。如果你意识到了面向对象开发思想的重要性,请仔细学习这篇文章。 希望对你有帮助! 这篇详细地解释封装、继承和多态,并在最后提供一个综合示例来总结这三个…

PyQt介绍——弹框介绍和使用

PyQt介绍——弹框介绍和使用 一、QMessageBox QMessageBox是一种通用的弹出式对话框,用于显示消息,允许用户通过单击不同的标准按钮对消息进行反馈 QMessageBox类提供了许多常用的弹出式对话框,如提示、警告、错误、询问、关于等对话框。这…

Hyper-v 新建 Windows 虚拟机卡在“Press any key to boot from CD or DVD...,无法按下任何按键

Hyper-v 新建 Windows 虚拟机卡在“Press any key to boot from CD or DVD…,无法按下任何按键 在显示这个界面之后点击启动,之后立刻狂按F2, 然后就能进去了

​代码混淆的原理是什么?常见代码混淆方法介绍

本文主要想你介绍代码混淆的原理,常见代码混淆方法,欢迎查阅~ 移动应用代码安全非常重要,代码逆向会导致代码逻辑被获取,进一步导致控制流被hook,安全防线被破,给APP安全带来巨大风险,因此开发者…

淘宝扭蛋机小程序:扭转购物新风尚,开启惊喜连连之旅

随着移动互联网的飞速发展,淘宝作为国内领先的电商平台,始终致力于为用户带来更加新颖、有趣的购物体验。如今,我们隆重推出淘宝扭蛋机小程序,将传统扭蛋机的乐趣与电商购物的便捷完美结合,为用户带来前所未有的惊喜与…

PyTorch构建自然语言处理模型

一、整体流程 二、 详细步骤 1. 准备数据 在构建自然语言处理模型之前,首先需要准备数据。可以使用PyTorch提供的Dataset和DataLoader类来加载和处理数据。 # 导入必要的库 import torch from torch.utils.data import Dataset, DataLoader # 定义自定义Dataset类…

Linux进程控制篇

1. 进程创建 fork()函数创建一个进程: 父进程返回子进程的pid子进程返回0 创建进程后,我们希望子进程做的事有两种: 子进程帮父进程完成同样的工作子进程干其他任务 进程 内核的相关管理数据结构(tack_struct mm_struct 页表) 代码和数据…

python零基础入门笔记【源源老师】

1. print() 输出 (1)认识英文单词 print: 输出(2)print() 的作用 print():用于在控制台上输出你想要的内容。 (3)代码演示 举例1: 【注意:】用双引号包裹的&#xff0…

OpenHarmony开发实例:【新闻客户端】

介绍 本篇Codelab我们将教会大家如何构建一个简易的OpenHarmony新闻客户端(JS版本)。应用包含两级页面,分别是主页面和详情页面,两个页面都展示了丰富的UI组件,其中详情页的实现逻辑中还展示了如何通过调用相应接口&a…

交友盲盒1.4.5

本文来自:微擎交友盲盒1.4.5 - 源码1688 应用介绍 品牌其他语言PHP数据库Mysql移动端Wap自适应公众服务号大小80 MB规格整站源码授权免授权源文件完全开源(含全部源文件)伪静态需要操作系统Windows,Linux安装方式QQ远程协助web服…

客户资料不翼而飞?企业数据保护攻略

在数字化经济时代,企业的客户资料等同于商业生命线,一旦泄露,后果不堪设想。例如,2017年Equifax的数据泄露事件,造成超过1.4亿用户的个人信息外泄,不仅给用户带来风险,也让公司名誉受损&#xf…

IDC发布2023年中国整体超融合市场报告,深信服第一

4月15日,IDC发布了《中国软件定义存储 (SDS)及超融合存储系统 (HCI)市场季度跟踪报告,2023年第四季度》。 报告显示,中国超融合市场在2023年较去年同期实现2.9%增长,其中HCI 验证系统市场占有率较去年同期上升近4%,接近…
最新文章