5

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?

1
  • Have you found it's solution? I am also facing same issue.
    – Abbas
    Commented Oct 23, 2018 at 12:19

2 Answers 2

7

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.

9
  • Of course , do not ever use object manager in your code unless you are creating custom factory or proxy class. And '*' is very inefficient way to build collections... Commented Nov 14, 2017 at 11:03
  • yes, you are right but its just for information.
    – Meetanshi
    Commented Nov 14, 2017 at 11:05
  • And as a result we have to deal with modules making eyes bleeding every day... And I got feeling that he already have collection object created, isn't he? Commented Nov 14, 2017 at 11:07
  • But I believe Magento\Catalog\Model\ResourceModel\Product\CollectionFactory does not available on Magento 2.2?
    – nuwaus
    Commented Nov 14, 2017 at 11:14
  • ..and yes, I'm using class injection from the constructor, not object manager.
    – nuwaus
    Commented Nov 14, 2017 at 11:16
1

This should work unless:

  • Store do not exists
  • You have already loaded collection items in some part of code that we do not see
  • The products actually are in the store in filter

Another thing is that you started with collection but the question is about single product in a store. To get a single product you could use ProductRepository->get or getById Both can be parameterized with storeId

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.