Given a Prisma schema (version 3.7.0) that looks like this:
model Category {
id String @id @default(cuid())
name String
transactions Transaction[]
}
model Transaction {
id String @id @default(cuid())
date Int
category Category @relation(fields: [categoryId], references: [id])
categoryId String
amount Float
notes String? @db.LongText
}
I want to basically write the following query using Prisma:
SELECT
t.categoryId,
c.name,
c.income,
SUM(t.amount) AS total
FROM Transaction t
JOIN Category c ON t.categoryID=c.id
WHERE t.date >= <start date> AND t.date < <end date>
GROUP BY t.categoryId;
I know I can aggregate on the Category table with something like this:
prisma.transaction.groupBy({
by: ['categoryId'],
_sum: { amount: true },
where: {
AND: [
{ date: { gte: startDate } },
{ date: { lt: endDate } },
]
},
});
But I can't figure out how to include the name
column from the Category
table.
I saw this question which asks for a solution to this problem. In this question, the author writes
I'm not exactly sure how/whether I can achieve something similar with Prisma, because as it stands right now, it seems like this would require two separate queries, which isn't optimal because there is sometimes the need for 2 or 3 joins or SELECTs from other tables.
The accepted answer to the question goes ahead & solves the problem with two separate queries, so I'm left wondering if there is a way to do this in one query.