メインコンテンツへスキップ

TypeScript と PlanetScale を使用したデータベースのクエリ

Prisma Client で最初のクエリを作成する

Prisma Client を生成したので、データベースのデータを読み書きするクエリの作成を開始できます。このガイドでは、プレーンな Node.js スクリプトを使用して Prisma Client のいくつかの基本的な機能を探索します。

`index.ts` という名前の新規ファイルを作成し、以下のコードを追加します

index.ts
import { PrismaClient } from './generated/prisma'

const prisma = new PrismaClient()

async function main() {
// ... you will write your Prisma Client queries here
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})

コードスニペットの各部分の簡単な概要です

  1. `@prisma/client` ノードモジュールから `PrismaClient` コンストラクターをインポートします
  2. `PrismaClient` をインスタンス化します
  3. データベースにクエリを送信する `main` という名前の `async` 関数を定義します
  4. `main` 関数を呼び出します
  5. スクリプト終了時にデータベース接続を閉じます

`main` 関数内に、データベースからすべての `User` レコードを読み込み、結果を出力する以下のクエリを追加します

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

このコマンドでコードを実行します

npx tsx index.ts

データベースにはまだ `User` レコードがないため、空の配列が出力されます

[]

データベースへのデータ書き込み

前のセクションで使用した `findMany` クエリは、データベースからデータを読み取るだけでした(まだ空でしたが)。このセクションでは、`Post` および `User` テーブルに新しいレコードを書き込むクエリを作成する方法を学びます。

`main` 関数を調整して、`create` クエリをデータベースに送信します

index.ts
async function main() {
await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
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 })
}

このコードは、[ネストされた書き込み](https://prisma.dokyumento.jp/docs/orm/prisma-client/queries/relation-queries#nested-writes)クエリを使用して、新しい `User` レコードと、新しい `Post` および `Profile` レコードを作成します。`User` レコードは、それぞれ `Post.author` ↔ `User.posts` および `Profile.user` ↔ `User.profile` の[リレーションフィールド](https://prisma.dokyumento.jp/docs/orm/prisma-schema/data-model/relations#relation-fields)を介して、他の2つのレコードに接続されています。

返される `User` オブジェクトに `posts` および `profile` リレーションを含めるよう Prisma Client に指示する [`include`](https://prisma.dokyumento.jp/docs/orm/prisma-client/queries/select-fields#return-nested-objects-by-selecting-relation-fields) オプションを `findMany` に渡していることに注意してください。

このコマンドでコードを実行します

npx tsx index.ts

出力は以下のようになります

[
{
email: 'alice@prisma.io',
id: 1,
name: 'Alice',
posts: [
{
content: null,
createdAt: 2020-03-21T16:45:01.246Z,
updatedAt: 2020-03-21T16:45:01.246Z,
id: 1,
published: false,
title: 'Hello World',
authorId: 1,
}
],
profile: {
bio: 'I like turtles',
id: 1,
userId: 1,
}
}
]

また、`allUsers` は [Prisma Client の生成された型](https://prisma.dokyumento.jp/docs/orm/prisma-client/type-safety/operating-against-partial-structures-of-model-types)のおかげで、静的に型付けされていることに注意してください。エディタで `allUsers` 変数にカーソルを合わせると型を確認できます。以下のように型付けされているはずです。

const allUsers: (User & {
posts: Post[]
})[]

export type Post = {
id: number
title: string
content: string | null
published: boolean
authorId: number | null
}

クエリにより、`User` および `Post` テーブルに新しいレコードが追加されました

User

idemailname
1"alice@prisma.io""Alice"

Post

idcreatedAtupdatedAttitlecontentpublishedauthorId
12020-03-21T16:45:01.246Z2020-03-21T16:45:01.246Z"Hello World"nullfalse1

Profile

idbiouserId
1"I like turtles"1

: `Post` テーブルの `authorId` 列と `Profile` テーブルの `userId` 列の番号はどちらも `User` テーブルの `id` 列を参照しており、`id` 値 `1` はデータベース内の最初の(そして唯一の)`User` レコードを指します。

次のセクションに進む前に、先ほど作成した `Post` レコードを `update` クエリを使用して「公開」します。`main` 関数を以下のように調整します

index.ts
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}

前と同じコマンドを使用してコードを実行します

npx tsx index.ts

以下の出力が表示されます

{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 1
}

`id` が `1` の `Post` レコードがデータベースで更新されました

Post

idtitlecontentpublishedauthorId
1"Hello World"nulltrue1

素晴らしい!Prisma Client を使用して、初めてデータベースに新しいデータを書き込みました 🚀

© . All rights reserved.