3

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?

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

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.

  • 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... – Bartosz Herba Nov 14 '17 at 11:03
  • yes, you are right but its just for information. – Meetanshi Nov 14 '17 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? – Bartosz Herba Nov 14 '17 at 11:07
  • But I believe Magento\Catalog\Model\ResourceModel\Product\CollectionFactory does not available on Magento 2.2? – nuwaus Nov 14 '17 at 11:14
  • ..and yes, I'm using class injection from the constructor, not object manager. – nuwaus Nov 14 '17 at 11:16
1

This should work unless: 1. Store do not exists 2. You have already loaded collection items in some part of code that we do not see 3. 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, privacy policy and cookie policy

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