2

I need to filter the products by store. However, after many try for almost a day, I can't filter products by store.

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 

        $productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
        $collection = $productCollectionFactory->create();


        // filter current store products
        $collection->addStoreFilter();
        $collection->addFieldToFilter('entity_id', ['in' => $best_selling_product_id]);

$best_selling_product_id is an array of product ID's. However, above code returns products from all stores.

Can someone help me here?

1

Try this:

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 

    $productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
    $collection = $productCollectionFactory->create();


    // filter current store products
    $storeid = 1; 
    $collection->addAttributeToSelect('*');
    $collection->addStoreFilter($storeid);
    $collection->addFieldToFilter('entity_id', ['in' => $best_selling_product_id]);
  • Actually, I have given a try for this too – Butterfly Apr 14 at 13:20
  • updated above code, please try – fmsthird Apr 14 at 13:24
  • ok, hold on a moment – Butterfly Apr 14 at 13:27
  • I wish it should work. But Unfortunately no luck. – Butterfly Apr 14 at 13:32
  • 1
    I've observed an odd behaviour. When I print foreach ($collection as $key => $value) { echo '<pre>'; print_r($value->getData()); echo '</pre>'; }, store_id changes for the same product to selected store. – Butterfly Apr 14 at 13:40
1

Use below code

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
        // filter current store products
$collection->setStore($storeManager->getStore());
$collection->addFieldToFilter('entity_id', ['in' => $best_selling_product_id]);

Note: Do not use objectmanager directly, add dependency to your respective file and use from it

  • Oops... No luck – Butterfly Apr 16 at 8:34

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.