I want the total quantity of all available products of all categories. I know there is ->getStockItem()->getQty()
but this is only for each product and not for all products.
For now I loop the categies and count the products, but so the inactive products get also counted:
$sum = 0;
for($i=3; $i <= 18; $i++) {
$categoryI = $categoryFactory->create()->load($i);
echo $categoryI->getProductCount();
$sum+= $categoryI->getProductCount();
echo ' ';
}
echo 'Summe: ';
echo $sum;
Is there an easy and clean way to get the sum of all active products which are in stock? Thanks
There is no "built in" way to do that by category. If you want to count enabled products, but only for certain categories, you can use something like this:
In your construct:
protected $_productCollectionFactory;
public function __construct(
// ...
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
// ...
) {
// ...
$this->_productCollectionFactory = $productCollectionFactory;
// ...
}
And in your function:
$sum = 0;
for($i=3; $i <= 18; $i++) {
$product_collection = $this->_productCollectionFactory->create();
$product_collection ->addCategoryFilter($category);
$product_collection ->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$sum += $product_collection->count();
}
This way you have the product attribute data available, so you can work with every product individuality. For your usecase, you could totally omit the categories entirely since you want the entire product count using
$sum = 0;
$product_collection = $this->_productCollectionFactory->create();
$product_collection ->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$sum = $product_collection->count();