データベースのクエリ
Prisma Clientで最初のクエリを作成する
Prisma Clientを生成したので、データベース内のデータを読み書きするクエリの作成を開始できます。このガイドの目的のために、Prisma Clientの基本的な機能をいくつか試すために、プレーンなNode.jsスクリプトを使用します。
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)
})
コードスニペットのさまざまな部分の簡単な概要を以下に示します。
- @prisma/client nodeモジュールからPrismaClientコンストラクタをインポートします。
- PrismaClientをインスタンス化します。
- データベースにクエリを送信するために、mainという名前のasync関数を定義します。
- main関数を呼び出します。
- スクリプトが終了したら、データベース接続を閉じます。
main関数内で、データベースからすべてのUserレコードを読み取り、結果を出力するために、次のクエリを追加します。
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関数を調整します。
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.author ↔ User.postsおよびProfile.user ↔ User.profileのリレーションフィールドを介して他の2つのレコードに接続されています。
includeオプションをfindManyに渡していることに注意してください。これは、Prisma Clientに、返されたUserオブジェクトのリレーションであるpostsとprofileを含めるように指示します。
次のコマンドでコードを実行します。
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
id | name | |
---|---|---|
1 | "alice@prisma.io" | "Alice" |
Post
id | createdAt | updatedAt | title | content | published | authorId |
---|---|---|---|---|---|---|
1 | 2020-03-21T16:45:01.246Z | 2020-03-21T16:45:01.246Z | "Hello World" | null | false | 1 |
Profile
id | bio | userId |
---|---|---|
1 | "I like turtles" | 1 |
注: PostのauthorId列とProfileのuserId列の数値は両方ともUserテーブルのid列を参照しています。つまり、id値1の列は、データベース内の最初(そして唯一)のUserレコードを参照しています。
次のセクションに進む前に、updateクエリを使用して、作成したばかりのPostレコードを「公開」します。main関数を次のように調整します。
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
id | title | content | published | authorId |
---|---|---|---|---|
1 | "Hello World" | null | true | 1 |
素晴らしい、Prisma Clientを使用して初めてデータベースに新しいデータを書き込みました🚀