Open16

Prisma素振り

島袋恵島袋恵

導入

$ yarn add prisma
$ yarn prisma init

上記コマンドを実行すると prisma/schema.prisma.env が自動生成された

島袋恵島袋恵

マイグレーション

$ prisma migrate dev

// マイグレーション名を入力する
? Enter a name for the new migration: › add user

Applying migration `20211023013115_add_user`

The following migration(s) have been created and applied from new schema changes:

migrations/
  └─ 20211023013115_add_user/
    └─ migration.sql

Your database is now in sync with your schema.

✔ Generated Prisma Client (3.2.1) to ./node_modules/@prisma/client in 77ms
  • prisma migrate dev を実行するたびに現状のスキーマとの差分のマイグレーションファイルが生成され、実行までされる
  • ドキュメントの参考箇所
    👇

https://www.prisma.io/docs/concepts/components/prisma-migrate

島袋恵島袋恵

APIからPrisma使ってDB操作する

TypeScript用のPrismaクライアント導入

$ yarn add @prisma/client
島袋恵島袋恵

はまったところ

スキーマの命名

https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#naming-conventions

  • ほんとはmodelは 単数、UpperCamel、field名はcamelCase にしないといけなかったんだけど、テーブル名に合わせて複数形で書いてしまった!!!!!!!!
  • mapを使うべき 👇. (あとでなおそう)

https://www.prisma.io/docs/concepts/components/prisma-schema/data-model#mapping-model-names-to-tables-or-collections

島袋恵島袋恵

ここまでの感想

  • prisma studio みやすい。便利。
  • prisma client からのDB操作するときのコードの書き心地よいいい感じ(複雑なクエリ書くとかなるとむずそう!?!?)
  • スキーマファイルの更新の差分からmigrationファイル生み出してくれて実行してくれるのめっちゃよい!!!
    (普段 Laravel 使っててmigrationファイルの方を手動で書いてるんだけど、それをしなくていいのが便利!!!)
  • ドキュメントわかりやすい