fix: GetByCategoryIdAsync incluye productos de categorías ancestras (CTE recursivo)
This commit is contained in:
@@ -46,12 +46,26 @@ public class ProductRepository : IProductRepository
|
|||||||
public async Task<IEnumerable<Product>> GetByCategoryIdAsync(int categoryId)
|
public async Task<IEnumerable<Product>> GetByCategoryIdAsync(int categoryId)
|
||||||
{
|
{
|
||||||
using var conn = _db.CreateConnection();
|
using var conn = _db.CreateConnection();
|
||||||
|
// CTE recursivo: sube por la jerarquía de categorías para incluir
|
||||||
|
// productos asignados al rubro solicitado O a cualquiera de sus ancestros.
|
||||||
|
// Ejemplo: consultando "Autos" devuelve productos de "Autos" Y de "Vehículos".
|
||||||
var sql = @"
|
var sql = @"
|
||||||
SELECT p.*, c.Name as CompanyName, pt.Code as TypeCode
|
WITH CategoryAncestors AS (
|
||||||
|
-- Nodo raíz: la categoría pedida
|
||||||
|
SELECT Id, ParentId FROM Categories WHERE Id = @CategoryId
|
||||||
|
UNION ALL
|
||||||
|
-- Subir un nivel: el padre de cada nodo ya en el CTE
|
||||||
|
SELECT c.Id, c.ParentId
|
||||||
|
FROM Categories c
|
||||||
|
INNER JOIN CategoryAncestors ca ON c.Id = ca.ParentId
|
||||||
|
)
|
||||||
|
SELECT p.*, comp.Name as CompanyName, pt.Code as TypeCode
|
||||||
FROM Products p
|
FROM Products p
|
||||||
JOIN Companies c ON p.CompanyId = c.Id
|
JOIN Companies comp ON p.CompanyId = comp.Id
|
||||||
JOIN ProductTypes pt ON p.ProductTypeId = pt.Id
|
JOIN ProductTypes pt ON p.ProductTypeId = pt.Id
|
||||||
WHERE p.CategoryId = @CategoryId AND p.IsActive = 1";
|
WHERE p.CategoryId IN (SELECT Id FROM CategoryAncestors)
|
||||||
|
AND p.IsActive = 1
|
||||||
|
OPTION (MAXRECURSION 20)";
|
||||||
return await conn.QueryAsync<Product>(sql, new { CategoryId = categoryId });
|
return await conn.QueryAsync<Product>(sql, new { CategoryId = categoryId });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user