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

データベースのクエリ

Prisma Client で最初のクエリを書く

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

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

index.ts
import { PrismaClient } from '@prisma/client'

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 node モジュールから 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 テーブルに新しいレコードを書き込むクエリを記述する方法を学びます。

create クエリをデータベースに送信するように main 関数を調整します。

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 })
}

このコードは、ネストされた書き込みクエリを使用して、新しい Post レコードと Profile レコードとともに新しい User レコードを作成します。User レコードは、Post.authorUser.posts および Profile.userUser.profile リレーションフィールド を介して他の 2 つのレコードに接続されています。

include オプションを findMany に渡していることに注意してください。これは、返された User オブジェクトのリレーションである postsprofile を含めるように Prisma Client に指示します。

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

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 の生成された型のおかげで静的に型付けされています。エディターで 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

: PostauthorId 列と ProfileuserId 列の数値は、両方とも User テーブルの id 列を参照しています。つまり、id1 列は、データベース内の最初の(そして唯一の)User レコードを参照しています。

次のセクションに進む前に、update クエリを使用して、作成した Post レコードを「公開」します。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
}

id1Post レコードがデータベースで更新されました。

Post

idtitlecontentpublishedauthorId
1"Hello World"nulltrue1

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