From fb47a11712619b2499ae380c3794643ca932c532 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Fri, 28 Jun 2024 18:00:07 +0700 Subject: [PATCH] feat: stats relation --- src/controllers/product/group-controller.ts | 32 ++++++++++++++++++++- src/controllers/product/type-controller.ts | 5 ++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/controllers/product/group-controller.ts b/src/controllers/product/group-controller.ts index 12ef7c5..2d676c4 100644 --- a/src/controllers/product/group-controller.ts +++ b/src/controllers/product/group-controller.ts @@ -66,6 +66,13 @@ export class ProductGroup extends Controller { const [result, total] = await prisma.$transaction([ prisma.productGroup.findMany({ + include: { + _count: { + select: { + type: true, + }, + }, + }, orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }], where, take: pageSize, @@ -74,7 +81,30 @@ export class ProductGroup extends Controller { prisma.productGroup.count({ where }), ]); - return { result, page, pageSize, total }; + const statsProduct = await prisma.productType.findMany({ + include: { + _count: { select: { product: true } }, + }, + where: { + productGroupId: { in: result.map((v) => v.id) }, + }, + }); + + return { + result: result.map((v) => ({ + ...v, + _count: { + ...v._count, + product: statsProduct.reduce( + (a, c) => (c.productGroupId === v.id ? a + c._count.product : a), + 0, + ), + }, + })), + page, + pageSize, + total, + }; } @Get("{groupId}") diff --git a/src/controllers/product/type-controller.ts b/src/controllers/product/type-controller.ts index 4739130..786c1da 100644 --- a/src/controllers/product/type-controller.ts +++ b/src/controllers/product/type-controller.ts @@ -68,6 +68,11 @@ export class ProductType extends Controller { } satisfies Prisma.ProductTypeWhereInput; const [result, total] = await prisma.$transaction([ prisma.productType.findMany({ + include: { + _count: { + select: { product: true }, + }, + }, orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }], where, take: pageSize,