TypeScriptとSQL Serverを使用してデータベースをクエリする
Prisma Clientで最初のクエリを記述する
Prisma Clientを生成したので、データベースのデータの読み書きを行うクエリを記述できます。このガイドでは、プレーンなNode.jsスクリプトを使用して、Prisma Clientの基本的な機能をいくつか試します。
`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)
})
コードスニペットの各部分の概要は次のとおりです
- `@prisma/client` ノードモジュールから `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` テーブルに新しいレコードを書き込むクエリの記述方法を学びます。
`main` 関数を調整して、`create` クエリをデータベースに送信します
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 })
}
このコードは、ネストされた書き込みクエリを使用して、新しい `User` レコードと、新しい `Post` および `Profile` レコードを作成します。`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` テーブルに新しいレコードを追加しました
ユーザー
id | メール | 名前 |
---|---|---|
1 | "alice@prisma.io" | "Alice" |
投稿
id | 作成日時 | 更新日時 | タイトル | 内容 | 公開済み | 著者ID |
---|---|---|---|---|---|---|
1 | 2020-03-21T16:45:01.246Z | 2020-03-21T16:45:01.246Z | "Hello World" | null | false | 1 |
プロフィール
id | 自己紹介 | ユーザーID |
---|---|---|
1 | "I like turtles" | 1 |
注: `Post` の `authorId` 列と `Profile` の `userId` 列の数値は、両方とも `User` テーブルの `id` 列を参照しています。したがって、`id` 値 `1` は、データベース内の最初の(かつ唯一の)`User` レコードを参照します。
次のセクションに進む前に、先ほど作成した `Post` レコードを `update` クエリを使用して「公開」します。`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` レコードがデータベースで更新されました
投稿
id | タイトル | 内容 | 公開済み | 著者ID |
---|---|---|---|---|
1 | "Hello World" | null | true | 1 |
素晴らしい!Prisma Clientを使って初めてデータベースに新しいデータを書き込みました🚀