Certainly! Here’s how you can write this SQL query as a Prisma Client query in JavaScript/TypeScript:
SQL Query
SELECT name, COUNT(*)
FROM orders
JOIN users ON users.id = orders.user_id
GROUP BY name
HAVING COUNT(*) > 3;
Prisma Equivalent
Assumptions:
Order is the Prisma model for the orders table.
User is the Prisma model for the users table.
Order model has a userId field that relates to User's id.
- You want to get user names and the count of their orders, only for users who have >3 orders.
Prisma Query
const result = await prisma.user.findMany({
select: {
name: true,
_count: {
select: { orders: true }
}
},
include: {},
where: {
orders: {
some: {}
}
},
having: {
orders: {
_count: {
gt: 3
}
}
},
// Prisma as of June 2024 doesn't natively support `HAVING` on `findMany`.
// Instead, fetch all, then filter in JS:
});
But Prisma does not yet support HAVING clauses directly. You’d typically fetch the grouped counts and filter in application code.
Practical Solution
const usersWithOrderCounts = await prisma.user.findMany({
select: {
name: true,
orders: {
select: { id: true }
}
}
});
const result = usersWithOrderCounts
.map(user => ({
name: user.name,
orderCount: user.orders.length,
}))
.filter(user => user.orderCount > 3);
Notes
prisma.user.findMany fetches users with their orders.
- We count orders per user in JavaScript.
- Filter for users with more than 3 orders.
If you have Prisma 4.13+ and use groupBy (experimental):
const grouped = await prisma.order.groupBy({
by: ['userId'],
_count: { userId: true },
having: {
userId: {
_count: { gt: 3 }
}
}
});
But then you'd need to join userId to get name. So, the filtering + mapping approach above is most flexible with current Prisma.
Summary:
Fetch users and their orders, count in JS, filter for users with >3 orders. Direct SQL-style HAVING in Prisma is limited, so post-process in JS.