【操作记录】在本地环境中设置Next.js项目中的Prisma

开发环境

$ sw_vers 
ProductName:            macOS
ProductVersion:         13.5.1
BuildVersion:           22G90

$ node -v
v19.2.0

$ npm -v
8.19.3

$ npx next -v
Next.js v13.4.19

前提是中文母语。

    • Next.jsプロジェクトの初期設定は済んでいるものとする

 

    DBはPostgreSQLを使用

文件结构

Project-Directory-Name
    ├─ .next
    ├─ node_modules
    ├─ public
    ├─ src
        └ pages
        └ styles
    ├─ .env
    ├─ .eslintrc.json
    ├─ .gitignore
    ├─ next-env.d.ts
    ├─ next.config.js
    ├─ package-lock.json
    ├─ package.json
    ├─ postcss.config.js
    ├─ README.md
    ├─ tailwind.config.js
    └  tsconfig.json

1. 安装 Prisma

# Prisma をインストール
$ npm install prisma --save-dev

# Prisma をセットアップ
$ npx prisma init --datasource-provider PostgreSQL

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

warn You already have a .gitignore file. Don't forget to add `.env` in it to not commit any private information.

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
スクリーンショット 2023-09-12 14.09.57.png

2. 准备DB服务器 DB

    • ローカル環境で開発するので自分でDBサーバーをたてる必要がある

 

    • DBサーバーにPostgreSQLを使用

PostgreSQL Mac OS をインストール

3. 准备好DB客户端

    Table Plusを使用

3.1 设置与DB服务器的连接

スクリーンショット 2023-09-13 0.14.41.png

创建逻辑数据库3.2

スクリーンショット 2023-09-13 0.02.34.png

4. 创建DB的ER图(数据建模)

根据ER图创建Prisma模式。

model Event {
  id               Int      @id @default(autoincrement())
  StartDateTime    DateTime
  EndDateTime      DateTime
  ParticipantCount Int
}

生成Migration文件并将其反映到数据库中。

创建一个.env.local文件,并在其中定义DATABASE_URL。

DATABASE_URL="DBのプロトコル://user名:password@ホスト名:ポート番号/DB名?schema=スキーマ名"
    PostgreSQLにおけるスキーマは複数のテーブルをグルーピングするもの(フォルダみたいなもの)。今回は、デフォルトで設定されてるpublicスキーマを使用する

为了从Prisma中读取.env.local文件,需要安装dotenv-cli。

    Next.jsは.env、.env.localを自動的に読み込む(.env.localが優先)が、Prismaはデフォルトだと.envしか読み込まないので、.env.localを読み込むためにdotenv-cliを使う
$ npm install --save-dev dotenv-cli

使用dotenv-cli可以将适用于您正在操作的环境的连接URL加载进来。
参考:使用多个.env文件。

执行6.3版本的Prisma Migrate

./node_modules/.bin/dotenv -e .env.local -- npx prisma migrate dev --name init
スクリーンショット 2023-09-15 17.40.01.png

可以在Table Plus中确认数据库内是否已创建了表格。

スクリーンショット 2023-09-15 17.34.28.png

以上是Prisma设置完成。

参考网站

    • Prisma Docs – https://www.prisma.io/docs/getting-started/quickstart

デフォルトの環境変数 – https://nextjs-ja-translation-docs.vercel.app/docs/basic-features/environment-variables#%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88%E3%81%AE%E7%92%B0%E5%A2%83%E5%A4%89%E6%95%B0

PostgreSQLにおけるデータベース、スキーマ、テーブルの関係 – https://www.javadrive.jp/postgresql/schema/index1.html

广告
将在 10 秒后关闭
bannerAds