跳到主內容

使用 Prisma Migrate 搭配 JavaScript 和 MySQL

建立資料庫模式

在本指南中,你將使用 Prisma Migrate 來建立資料庫中的表。將以下 Prisma 資料模型新增到 prisma/schema.prisma 中的 Prisma 模式中

prisma/schema.prisma
model Post {
id Int @id @default(autoincrement())
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 @id @default(autoincrement())
bio String?
user User @relation(fields: [userId], references: [id])
userId Int @unique
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
profile Profile?
}

要將你的資料模型對映到資料庫模式,你需要使用 prisma migrate CLI 命令

npx prisma migrate dev --name init

此命令執行兩項操作

  1. 它為本次遷移建立了一個新的 SQL 遷移檔案
  2. 它針對資料庫執行 SQL 遷移檔案

注意:在執行 prisma migrate dev 後,generate 預設會在底層被呼叫。如果你的模式中定義了 prisma-client-js 生成器,它將檢查 @prisma/client 是否已安裝,如果缺失則會安裝。

太棒了,你現在已經使用 Prisma Migrate 在資料庫中建立了三張表 🚀

© . This site is unofficial and not affiliated with Prisma Data, Inc.