データベースをクエリする
Prisma Clientで最初のクエリを記述する
Prisma Clientを生成したので、データベース内のデータを読み書きするクエリを記述し始めることができます。このガイドでは、Prisma Clientの基本的な機能をいくつか試すために、プレーンなNode.jsスクリプトを使用します。
`index.js`という名前の新しいファイルを作成し、次のコードを追加します
const { PrismaClient } = require('@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)
}
次に、このコマンドでコードを実行します
node index.js
データベースに`User`レコードがまだないため、これは空の配列を出力するはずです
[]
データベースにデータを書き込む
前のセクションで使用した`findMany`クエリは、データベースからデータを*読み取る*だけです(まだ空でしたが)。このセクションでは、`Post`、`User`、および`Comment`テーブルに新しいレコードを*書き込む*ためのクエリを記述する方法を学びます。
`create`クエリをデータベースに送信するように`main`関数を調整します
async function main() {
await prisma.user.create({
data: {
name: 'Rich',
email: 'hello@prisma.com',
posts: {
create: {
title: 'My first post',
body: 'Lots of really interesting stuff',
slug: 'my-first-post',
},
},
},
})
const allUsers = await prisma.user.findMany({
include: {
posts: true,
},
})
console.dir(allUsers, { depth: null })
}
このコードは、ネストされた書き込みクエリを使用して、新しい`Post`とともに新しい`User`レコードを作成します。`User`レコードは、`Post.author` ↔ `User.posts`のリレーションフィールドを介してもう一方のレコードに接続されています。
`include`オプションを`findMany`に渡していることに注意してください。これは、返された`User`オブジェクトに`posts`リレーションを含めるようにPrisma Clientに指示します。
このコマンドでコードを実行します
node index.js
出力は次のようになります
[
{
id: '60cc9b0e001e3bfd00a6eddf',
email: 'hello@prisma.com',
name: 'Rich',
address: null,
posts: [
{
id: '60cc9bad005059d6007f45dd',
slug: 'my-first-post',
title: 'My first post',
body: 'Lots of really interesting stuff',
userId: '60cc9b0e001e3bfd00a6eddf',
},
],
},
]
クエリは、`User`テーブルと`Post`テーブルに新しいレコードを追加しました
ユーザー
id | メールアドレス | 名前 |
---|---|---|
60cc9b0e001e3bfd00a6eddf | "hello@prisma.com" | "Rich" |
投稿
id | 作成日 | タイトル | コンテンツ | 公開済み | authorId |
---|---|---|---|---|---|
60cc9bad005059d6007f45dd | 2020-03-21T16:45:01.246Z | "My first post" | たくさんの非常に興味深いもの | false | 60cc9b0e001e3bfd00a6eddf |
注: `Post`の`authorId`列の一意のIDは、`User`テーブルの`id`列を参照しています。つまり、`id`値`60cc9b0e001e3bfd00a6eddf`列は、データベース内の最初(および唯一)の`User`レコードを参照しています。
次のセクションに進む前に、`update`クエリを使用して、作成したばかりの`Post`レコードにいくつかのコメントを追加します。次のように`main`関数を調整します
async function main() {
await prisma.post.update({
where: {
slug: 'my-first-post',
},
data: {
comments: {
createMany: {
data: [
{ comment: 'Great post!' },
{ comment: "Can't wait to read more!" },
],
},
},
},
})
const posts = await prisma.post.findMany({
include: {
comments: true,
},
})
console.dir(posts, { depth: Infinity })
}
次に、前と同じコマンドを使用してコードを実行します
node index.js
次の出力が表示されます
[
{
id: '60cc9bad005059d6007f45dd',
slug: 'my-first-post',
title: 'My first post',
body: 'Lots of really interesting stuff',
userId: '60cc9b0e001e3bfd00a6eddf',
comments: [
{
id: '60cca420008a21d800578793',
postId: '60cca40300af8bf000f6ca99',
comment: 'Great post!',
},
{
id: '60cca420008a21d800578794',
postId: '60cca40300af8bf000f6ca99',
comment: "Can't wait to try this!",
},
],
},
]
素晴らしい、Prisma Clientを使用して初めてデータベースに新しいデータを書き込みました🚀