0
0

Prismaでviewを操作できるようにする

Last updated at Posted at 2024-09-09

はじめに

Prismaでviewを操作しようと思ったのですが、意外に記事が少なかったので実装方法を共有します。

ちなみに公式ドキュメントを確認するとしっかりと記述がありますが、より分かりやすく説明することを心がけます。

公式ドキュメント

初期設定

schema.prismaファイルにpreviewFeatures = ["views"]を設定する

schema.prisma
generator client {
  provider        = "prisma-client-js"
+ previewFeatures = ["views"]
}

コマンドなどでviewを作成しましょう

prismaから直接viewを追加することは2024年9月時点ではできないようです。

viewを追加しましょう ※以下イメージです。
mysqlでのview作成方法

CREATE VIEW UserInfo (
  id, 
  email, 
  name, 
  bio
) AS (
  SELECT 
    sa.id, 
    i.email, 
    i.name, 
    sh.bio
  FROM 
    sales sa 
    LEFT JOIN items i ON sa.item_id = i.id 
    LEFT JOIN shops sh ON sa.shop_id = sh.id
);

schema.prismaにviewを反映させる

以下のコマンドを実行します。

npx prisma db pull

するとschema.prismaにviewが反映します。

/// The underlying view does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
view UserInfo {
  id    Int?
  email String?
  name  String?
  bio   String?

  @@ignore
}

schema.prismaにviewの内容を編集する

上記のviewのブロックを有効化するには以下の条件を満たす必要があります。

  • 主キーのオプションフラグ?を削除する
  • 主キーに@uniqueを追加する
  • @@ignore属性を削除する
  • 上部に生成されたコメントを削除する
- /// The underlying view does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.

view UserInfo {
-  id    Int?
+  id    Int  @unique
   email String?
   name  String?
   bio   String?

-  @@ignore
}

以上でviewテーブル操作できるようになっています。

ちなみにこの時点でprisma/viewsディレクトリが自動生成され、sqlファイルが追加されています。

操作できるか確認してみましょう。

以下のようにするとuserInfoから全件データを取得できます。

const userinfo = await prisma.userInfo.findMany()

最後に

お疲れ様でした!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0