0

In product collection addAttributeToFilter is not working if we assing attribute value in only store view. But if we assing in default and store view than it working fine.

anyone have idea why it is happening ?

This is my code :

$products = $category->getProductCollection();
$products->addFieldToSelect('*');
$products->setStore($storeId);
$products->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()]);
$products->setVisibility($this->productVisibility->getVisibleInSiteIds());
  • Please post the code in question. – jafar pinjar May 16 at 10:23
1

You appear to doing a category product collection. Can you not use something like this?

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

    public function getProductCollection($storeId, $categories = [])
    {
        $collection = $this->productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addStoreFilter($storeid);  
        $collection->addCategoriesFilter(['in' => $categories]);
        $collection->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()]);
        $collection->setVisibility($this->productVisibility->getVisibleInSiteIds());      
        return $collection;
    }

https://github.com/magento/magento2/blob/2.3/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php#L923-L942

0

If you want to filter a collection on store-specific values (which seems to be the matter in your case), you should either use setStoreId() to make the collection aware of which store this collection applies to:

$productCollection
    ->setStoreId(int|string|\Magento\Store\Api\Data\StoreInterface $storeId);

You can also filter a collection on a store, which also includes the availability for the given store (like visibility):

$productCollection
    ->addStoreFilter(int|string|\Magento\Store\Api\Data\StoreInterface $storeId);

Although in your case, I suspect a setStoreId() would do the trick.

  • I have already do same way, Please check my question. – Niranjan Gondaliya May 16 at 11:31
  • Just inject store manager dependency and in your function add this code $collection->addStoreFilter($this->_storeManager->getStore()); – aravind May 16 at 12:37

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.