Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9145

Nexus + Prisma で Query の返却値の生成時に関連テーブルの内容も一緒に Where する

$
0
0
例えば、 - user というテーブルは company という所属会社の情報を関連として持っている。 - GraphQL の query からは、引数に所属会社名も含めて検索したい。 みたいなケース。 想定する input (query) は以下のような感じ。 クエリ query users ($input: UserWhereManyInput) { users (input: $input) { id name company { id name } } } 引数 { "companyName": "テスト株式会社" } これを実現します。 Query.ts import { arg, list, queryType } from "@nexus/schema"; import { User } from "./path/to/model"; export const Query = queryType({ definition(t) { t.field("users", { type: list(User), args: { input: arg({ type: "UserWhereManyInput", }), }, async resolve(_, args, context) { const id = args.input?.id; const companyName = args.input?.companyName; const user = await context.prisma.user.findMany({ where: { id, // company.name から検索 company: { name: { contains: companyName, }, }, }, }); return user; }, }); }, }); Prisma の検索系メソッドの引数のオプションを、上記のようにネスト表現することで関連テーブルの Where 検索もできるようです。 Nexus の context には Prisma が注入されていることを前提としています。 ちなみに UserWhereManyInput は以下のようなイメージ。 引数は平で受け取らずにちゃんと型をつくっておくと後々嬉しいことが多い気がするのでオススメです。 UserWhereManyInput.ts import { inputObjectType } from "@nexus/schema"; export const UserWhereManyInput = inputObjectType({ name: "UserWhereManyInput", definition(t) { t.nullable.int("id"); t.nullable.string("companyName"); }, }); これでいけると思います。

Viewing all articles
Browse latest Browse all 9145

Trending Articles