我的类别有/没有子类别。 还有属于一个或多个类别的产品。
我需要统计所有父类别(包括子类别)中的产品数量。
我得到以下PHP数组,其中数组键是类别ID,数组值表示父级ID、数据库中的ID以及最终类别的产品数量:
array:3000 [▼
1 => array:3 [▼
"id" => 30
"parent_id" => null
"count" => 0
]
2 => array:3 [▶]
21 => array:3 [▶]
211 => array:3 [▶]
212 => array:3 [▶]
213 => array:3 [▶]
2111 => array:3 [▼
"id" => 36
"parent_id" => 211
"count" => 0
]
21111 => array:3 [▼
"id" => 37
"parent_id" => 2111
"count" => 2510
]
//...
如何求父类别中所有子类别的产品数量之和?
很明显你需要使用循环,但我不明白如何使用:c
嗨,我有一个流程给你,
获取所有没有子项的产品类别
sql:
select pc.* from product_categories as pc
where pc.id != (select parent_product_category_id from product_categories as pc2)
现在假设您拥有所有没有任何子项的产品类别
$productCategoriesWithoutChildren = getProductCategoriesWithoutChildren(); // use sql that i gived to you
foreach ($productCategoriesWithoutChildren as $productCategory) {
$categoryId = $productCategory->getId();
$count = 0;
while(true) {
$category = getCategory($categoryId);
$count = $count + getCountForSingleCategory($category->getId()); // write it by yourself
saveCountForCategory($category->getId(), $count); // write it by yourself
$parentCategory = $category->getParent();
if(!$parentCategory){
break;
}
$categoryId = $parentCategory->getId();
}
}