Slackbot
11/09/2021, 2:36 AMRyan
11/09/2021, 6:13 AMMaciek K
11/09/2021, 9:33 AMexport const Account = objectType({
name: "User",
definition(t) {
t.nonNull.string("id");
t.nonNull.string("name");
t.field("ratingsCount", {
type: "Int",
resolve: (parent, _, ctx) =>
ctx.prisma.rating.count({ where: { userId: parent.id } }),
});
},
});
Then I can query it like:
query Users {
id
name
ratingsCount
}
But I'm not sure if that's the proper and performant way to do it.
Btw you would want to make that email field on user @unique
and query the user by .findUnique()
Maciek K
11/09/2021, 10:07 AMMaciek K
11/09/2021, 10:38 AMtype Account {
id
rooms Room[]
}
type Room {
id String @id @default(cuid()) @db.VarChar(30)
accountId String @db.VarChar(30)
account Account @relation(fields: [accountId], references: [id])
}
Nexus:
export const Account = objectType({
name: "Account",
definition(t) {
t.nonNull.string("id");
t.field("roomsCount", {
type: "Int",
resolve: (parent, _, ctx) =>
ctx.prisma.room.count({ where: { accountId: parent.id } }),
});
},
});
Querying from graphql playground:
query accounts {
id
roomsCount
}
I get sql query from prisma logs ( I have two accounts):
prisma:query SELECT "booking$dev"."Account"."id" FROM "booking$dev"."Account" WHERE 1=1 OFFSET $1
prisma:query SELECT COUNT(*) FROM (SELECT "booking$dev"."Room"."id" FROM "booking$dev"."Room" WHERE "booking$dev"."Room"."account" = $1 OFFSET $2) AS "sub"
prisma:query SELECT COUNT(*) FROM (SELECT "booking$dev"."Room"."id" FROM "booking$dev"."Room" WHERE "booking$dev"."Room"."account" = $1 OFFSET $2) AS "sub"
That's two count queries for two accounts.
When doing a prisma query (not by graphql):
ctx.prisma.account.findMany({ select: { id: true, _count: { select: { rooms: true } } } });
I get:
prisma:query SELECT "booking$dev"."Account"."id", "aggr_selection_0_Room"."_aggr_count_rooms" FROM "booking$dev"."Account" LEFT JOIN (SELECT "booking$dev"."Room"."account", COUNT(*) AS "_aggr_count_rooms" FROM "booking$dev"."Room" GROUP BY "booking$dev"."Room"."account") AS "aggr_selection_0_Room" ON ("booking$dev"."Account"."id" = "aggr_selection_0_Room"."account") WHERE 1=1 OFFSET $1
I'm not an SQL expert by any means. Is the latter more performant (with thousands of accounts) ?? Or should I not worry about this at all and difference will be neglectible?