[TOC]

What is Prisma?

Next-generation ORM for Node.js and TypeScript (next-generation ORM framework for Node.js) currently supports PostgreSQL, MySQL and SQLite.

Step by step creation

  1. Create a project directory

    • $ mkdir hello-prisma && cd hello-prisma
  2. Initialize the project and install the dependency files

    • $ npm init -y
    • $ npm install prisma typescript ts-node @types/node --save-dev
  3. Create tsconfig.json and enter the following

    • {
        "compilerOptions": {
          "sourceMap": true."outDir": "dist"."strict": true."lib": ["esnext"]."esModuleInterop": true}}Copy the code
  4. Create the Prisma Schema file

    • npx prisma init
      • The following files are generated
  5. Set the database and modify the provider attribute of PRISma /schema.prisma

    • Datasource db {// Provider can set three properties: mysql, sqlite, postgresql provider = "mysql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" }Copy the code
  6. //USER:PASSWORD@HOST:PORT/DATABASE? Mysql ://root:12345678@localhost:3432/mydb? schema=public

  7. Append to prisma/schema.prisma

    • model Post {
        id        Int      @default(autoincrement()) @id
        createdAt DateTime @default(now())
        updatedAt DateTime @updatedAt
        title     String   @db.VarChar(255)
        content   String?
        published Boolean  @default(false)
        author    User     @relation(fields: [authorId], references: [id])
        authorId  Int
      }
      
      model Profile {
        id     Int     @default(autoincrement()) @id
        bio    String?
        user   User    @relation(fields: [userId], references: [id])
        userId Int     @unique
      }
      
      model User {
        id      Int      @default(autoincrement()) @id
        email   String   @unique
        name    String?
        posts   Post[]
        profile Profile?
      }
      Copy the code
  8. Prisma Migrate dev –name init $NPX prisma Migrate dev –name init

The following files are generated:

  1. The installationPrisma Client: $ npm install @prisma/client
  2. createindex.tsEnter the following content
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  // ... you will write your Prisma Client queries here
  const allUsers = await prisma.user.findMany()
  console.log(allUsers)
}

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

NPX ts-node index. Ts: []

  1. Update man method

async function main() {
  // ... you will write your Prisma Client queries here
  await prisma.user.create({
    data: {
      name: 'Alice'.email: '[email protected]'.posts: {
        create: { title: 'Hello World'}},profile: {
        create: { bio: 'I like turtles'}},}})const allUsers = await prisma.user.findMany({
    include: {
      posts: true.profile: true,}})console.dir(allUsers, { depth: null})}Copy the code

The result of executing the code is

[
  {
    email: '[email protected]',
    id: 1,
    name: 'Alice',
    posts: [
      {
        content: null,
        createdAt: 2020- 03- 21T16:45:01.246Z,
        id: 1,
        published: false,
        title: 'Hello World',
        authorId: 1,
      }
    ],
    profile: {
      bio: 'I like turtles',
      id: 1,
      userId: 1,}}]Copy the code
  1. in Prisma StudioTo view the data:$ npx prisma studio

Select an item and see the data below

Refer to the address

  • www.prisma.io/docs/gettin…