Kent C. Dodds
08/19/2021, 8:17 PMmodel PostRead {
id String @id @default(uuid())
createdAt DateTime @default(now())
user User? @relation(fields: [userId], references: [id])
userId String?
clientId String?
postSlug String
}
I want to be able to get a count of distinct rows by userId and clientId (if the user isn't logged in, then I have a randomly generated ID for their client).
I've tried this:
prisma.postRead.groupBy({
_count: true,
by: ['userId', 'clientId'],
})
But that returns an array for each group with _count
which I can then add manually, but I'd prefer to do that in the db.
I've also tried count
, but I'm not sure what to put in my query... And I looked at aggregate but I can't figure out what I'd put in there either π€Kent C. Dodds
08/19/2021, 8:19 PMKent C. Dodds
08/19/2021, 8:42 PMasync function getReaderCount() {
// couldn't figure out how to do this in one query with out $queryRaw π€·ββοΈ
type CountResult = [{count: number}]
const [userIdCount, clientIdCount] = await Promise.all([
prisma.$queryRaw`SELECT COUNT(DISTINCT "public"."PostRead"."userId") FROM "public"."PostRead" WHERE ("public"."PostRead"."userId") IS NOT NULL` as Promise<CountResult>,
prisma.$queryRaw`SELECT COUNT(DISTINCT "public"."PostRead"."clientId") FROM "public"."PostRead" WHERE ("public"."PostRead"."clientId") IS NOT NULL` as Promise<CountResult>,
]).catch(() => [[{count: 0}], [{count: 0}]])
return userIdCount[0].count + clientIdCount[0].count
}
If anyone can help me figure out how to improve that, I would welcome the help πRyan
08/20/2021, 6:27 AM