class DashboardService {
// โ N+1 ๋ฐ์
async getDashboardSlow() {
const users = await UserModel.getPuri().select("id", "name");
const stats = [];
for (const user of users) {
const orderCount = await OrderModel.getPuri()
.select({ count: Puri.count() })
.where({ user_id: user.id });
const totalSpent = await OrderModel.getPuri()
.select({ total: Puri.sum("total") })
.where({ user_id: user.id });
stats.push({
user: user.name,
orderCount: orderCount[0].count,
totalSpent: totalSpent[0].total,
});
}
return stats;
}
// โ
JOIN์ผ๋ก ์ต์ ํ
async getDashboardFast() {
return UserModel.getPuri()
.select(
"users.id",
"users.name",
knex.raw("COUNT(orders.id) as order_count"),
knex.raw("COALESCE(SUM(orders.total), 0) as total_spent"),
)
.leftJoin("orders", "orders.user_id", "users.id")
.groupBy("users.id");
}
}