Prisma初体验【逆向生成数据模型】

Prisma逆向生成数据模型

初次体验Prisma工程搭建,在ORM领域表现不错。Prisma是一个面向Node.js和TypeScript的开源ORM。它用于替代编写普通的SQL,或使用另一种数据库访问工具,如SQL查询生成器(如knex.js)或ORMs(如TypeORM和Sequelize)。Prisma目前支持PostgreSQL、MySQL、SQLServer和SQLite。虽然Prisma可以与普通JavaScript一起使用,但它包含TypeScript,并提供了一种类型安全级别,超出TypeScript生态系统中其他Orm的保证范围。如下工程在window 10环境下的实施。

1.创建工程目录

D:\project\example\typeorm> mkdir hello-prisma
D:\project\example\typeorm> cd hello-prisma

2.项目初始化

D:\project\example\typeorm>npm init -y 
D:\project\example\typeorm>npm install prisma typescript ts-node @types/node --save-dev

3.创建tsconfig.json

在工程更目录下创建tsconfig.json,并添加如下配置信息:

{
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "lib": ["esnext"],
    "esModuleInterop": true
  }
}

注:可以使用tsc --init创建,windows系统需要识别tsc命令。

4.创建Prisma schema文件

在工程目录中使用如下命令创建Prisma schema文件(系统默认文件名为schema.prisma):

D:\project\example\typeorm> npx prisma init

5.工程目录

在这里插入图片描述
注意:index.ts文件为后期创建的文件。

6.配置数据信息

在工程目录中的.env文件中设置DATABASE_URL(本工程使用的mysql数据库):

DATABASE_URL="mysql://[用户名]:[密码]@localhost:3306/world?schema=public"

在prisma文件夹下的schema.prisma文件中修改数据库类型:

datasource db {
  provider = "mysql" //初始默认值为“postgresql”
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

7.逆向生成数据模型

使用如下命令生成数据模型【数据库中存在表数据】:

D:\project\example\typeorm> npx prisma introspect

在文件中系统会自动增加模型数据信息:

model post {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime
  title     String   @db.VarChar(255)
  content   String?
  published Boolean  @default(false)
  authorId  Int
  user      user     @relation(fields: [authorId], references: [id])

  @@index([authorId], name: "authorId")
}
//如下是新增model部分
model profile {
  id     Int     @id @default(autoincrement())
  bio    String?
  userId Int     @unique
  user   user    @relation(fields: [userId], references: [id])
}

model user {
  id      Int      @id @default(autoincrement())
  email   String   @unique
  name    String?
  post    post[]
  profile profile?
}

8.变更数据表中的信息

在工程目录文件中添加index.ts文件,其内容如下:

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
// ... you will write your Prisma Client queries here
//查询数据库中user的记录数据
const allUsers = await prisma.user.findMany()
console.log(allUsers)
  
//对user表进行添加数据
 await prisma.user.create({
   data: {
     name: 'Alice',
     email: 'alice@prisma.io',
     posts: {
       create: { title: 'Hello World' },
     },
     profile: {
       create: { bio: 'I like turtles' },
     },
   },
 })
//查找数据
 const allUsers1 = await prisma.user.findMany({
   include: {
     posts: true,
     profile: true,
   },
 })
 console.dir(allUsers1, { depth: null })
//更新post数据
 const post = await prisma.post.update({
   where: { id: 1 },
   data: { published: true },
 })
 console.log(post)
 
 const posts = await prisma.profile
  .findUnique({
    where: { id: 1 },
  })
  .user()
  .posts()
  console.log(posts)
}
main()
  .catch(e => {
    throw e
  })
  .finally(async () => {
    await prisma.$disconnect()
})

9.执行index.ts文件

使用如下命令执行index.ts脚本:

D:\project\example\typeorm> npx ts-node index.ts

总结,简单、明了、高效,让程序员更加关注业务。Typeorm同样是体验性很好的ORM,就是在逆向工程方面在npm v7版本下bug问题,大多是包不兼容问题。后期会继续研究与整合新组件或框架,搭建一个高效的研发平台架构。敬请关注,谢谢!

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,我可以帮你回答这个问题。 首先,你需要安装并配置好 Prisma。然后,你可以使用以下命令来创建一个新的 Prisma 数据模型: ``` prisma init ``` 这将创建一个新的 Prisma 项目,并在其中包含一个 `datamodel.prisma` 文件。你需要在这个文件中定义 Conduit 应用程序的数据模型。 以下是一个示例数据模型,其中包含了 Conduit 应用程序中的一些基本实体和关系: ``` // datamodel.prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") } model User { id Int @id @default(autoincrement()) username String @unique email String @unique password String bio String? image String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt follows User[] @relation("Follow", references: [id]) followers User[] @relation("Follow", references: [id]) articles Article[] comments Comment[] } model Article { id Int @id @default(autoincrement()) slug String @unique title String description String body String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt author User @relation("Author", fields: [authorId], references: [id]) authorId Int favorites User[] @relation("Favorite", references: [id]) comments Comment[] } model Comment { id Int @id @default(autoincrement()) body String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt author User @relation(fields: [authorId], references: [id]) authorId Int article Article @relation(fields: [articleId], references: [id]) articleId Int } ``` 在这个数据模型中,我们定义了三个实体:User、Article 和 Comment。每个实体都有一些属性和关系。 例如,User 实体具有 username、email、password、bio、image、createdAt 和 updatedAt 属性。它还有一个 follows 和 followers 关系,用于表示用户之间的关注关系。User 实体还具有 articles 和 comments 关系,用于表示用户发表的文章和评论。 Article 实体具有 slug、title、description、body、createdAt 和 updatedAt 属性。它还有一个 author 关系,表示文章的作者。Article 实体还具有 favorites 和 comments 关系,用于表示用户喜欢的文章和文章的评论。 Comment 实体具有 body、createdAt 和 updatedAt 属性。它还有一个 author 和 article 关系,表示评论的作者和所属文章。 你可以根据自己的需求来定义数据模型,并使用 Prisma 自动创建数据库表和关系。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诀窍的心灵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值