Created
December 5, 2020 19:17
-
-
Save satishgumudavelli/80db70576137536604dc39475e702dfa to your computer and use it in GitHub Desktop.
Magento 2 get category collection with product count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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