Skip to content

Instantly share code, notes, and snippets.

@satishgumudavelli
Created December 5, 2020 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satishgumudavelli/80db70576137536604dc39475e702dfa to your computer and use it in GitHub Desktop.
Save satishgumudavelli/80db70576137536604dc39475e702dfa to your computer and use it in GitHub Desktop.
Magento 2 get category collection with product count
<?php
namespace Namespacename\Modulename\Helper;
use Magento\Catalog\Model\Indexer\Category\Product\TableMaintainer;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Helper\AbstractHelper;
class CategoryHelper extends AbstractHelper
{
/**
* @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
*/
private $categoryCollectionFactory;
/**
* @var TableMaintainer
*/
private $tableMaintainer;
/**
* Store manager
*
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* CategoryHelper constructor.
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param TableMaintainer|null $tableMaintainer
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
TableMaintainer $tableMaintainer = null
)
{
parent::__construct($context);
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->_storeManager = $storeManager;
$this->tableMaintainer = $tableMaintainer ?: ObjectManager::getInstance()->get(TableMaintainer::class);
}
public function getStoreId()
{
return $this->_storeManager->getStore()->getId();
}
public function getCategoryCollectionWithProductCount()
{
$categoryCollection = $this->categoryCollectionFactory->create();
$select = $categoryCollection->getSelect();
$select->joinLeft(
['cat_index' => $this->tableMaintainer->getMainTable($this->getStoreId())],
'cat_index.category_id=e.entity_id',
['product_count' => 'COUNT(DISTINCT cat_index.product_id)']
)->group('e.entity_id');
return $categoryCollection;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment