Magento – Get product collection by store ID on Magento 2.2

collection;filtermagento2productstore-id

I want to get all products by store ID, so I'm doing it like this

return $this->productCollection->addStoreFilter(27);

productCollection is

Magento\Catalog\Model\ResourceModel\Product\Collection

but instead, it returning the products by store, it returns all the products of all stores.

so can you please let me know how can I get only the product which belongs to store ID 27 or any given ID?

Best Answer

Please try this

<?php
namespace Meetanshi\Example\Block;
class Product extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
        array $data = []
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
    }

    public function getProductCollection()
    {
        $storeid = 27; 
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addStoreFilter($storeid);        
        return $collection;
    }
}
?>   

Hope this will help and make sure the id you are passing is available.

Related Topic