Optimize product retrieval by department categories and improve filtering in productsRoute
- Refactored `getAllProductInDepartmentCategories` in `departments_o` using `array_reduce` for cleaner and more efficient category loop. - Enhanced `productsRoute` to filter department-specific products using IDs for stricter matching.
This commit is contained in:
@@ -382,26 +382,21 @@ class departments_o extends db
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @return products_o[] An array of all products in the department's categories
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getAllProductInDepartmentCategories(): array
|
||||
{
|
||||
self::requireSelected();
|
||||
|
||||
// Get all the categories associated
|
||||
$department_categories = (new department_categories_o())->getDepartmentCategoryObjects($this->id);
|
||||
$categories = [];
|
||||
/** @var products_o[] $products */
|
||||
$products = [];
|
||||
foreach ( $department_categories as $department_category ) {
|
||||
$categories[] = $department_category->getCategory();
|
||||
}
|
||||
foreach ( $categories as $category ) {
|
||||
$cat_products = $category->getProducts();
|
||||
foreach ($cat_products as $cat_product) {
|
||||
$products[] = $cat_product;
|
||||
}
|
||||
}
|
||||
|
||||
// Use array_reduce to combine both loops into a single operation
|
||||
$products = array_reduce($department_categories, function ($products, $department_category) {
|
||||
return array_merge($products, $department_category->getCategory()->getProducts());
|
||||
}, []);
|
||||
|
||||
// Remove duplicate products
|
||||
return array_unique($products, SORT_REGULAR);
|
||||
}
|
||||
|
||||
@@ -245,12 +245,20 @@ class productsRoute
|
||||
if (isset($data['department_id'])) {
|
||||
// Get all product ids contained in a category attached to the department
|
||||
$departmentSpecificProducts = (new departments_o())->select((int)$data['department_id'])->getAllProductInDepartmentCategories();
|
||||
// Get the product ids as an array
|
||||
$departmentSpecificProductIds = array_map(function ($product) {
|
||||
return $product->id;
|
||||
}, $departmentSpecificProducts);
|
||||
// Return the list of products
|
||||
$response->success(
|
||||
(new products_o())->applyDepartmentPricing((array)(new products_o())->listObjectsWithPaginationIfSet(
|
||||
function ($product) {
|
||||
function ($product) use ($departmentSpecificProductIds) {
|
||||
// Only include products that are in the department specific product ids
|
||||
return parseProduct($product);
|
||||
},
|
||||
(new products_o())->forceRestrictFilters([
|
||||
'id' => $departmentSpecificProductIds
|
||||
])
|
||||
), (int)$data['department_id'])
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user