2

I need to filter comma sperated values in addAttributeToFilter in magento 2

Here is my Code:

$comma_separated_values = 26,27,28,29;

$categoryProducts = $category->getProductCollection()->addAttributeToSelect('*')->addAttributeToSort('position', 'ASC')->addAttributeToFilter('color', $comma_separated_values);

How I can pass in this?

2

You can try this:

$categoryProducts = $category
    ->getProductCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToSort('position', 'ASC')
    ->addAttributeToFilter('color', array('in',$comma_separated_values));

If you want to add category filter along with other collection just add this:

->addCategoriesFilter(array('in' => $categories))

Where $categories would be like $categories= '123,321';

  • Thanks for reply. Need to do same for $cat_id = 26,28; $category = $categoryFactory->create()->load($cat_id); – Shomita May 22 '19 at 6:15
  • I have updated my answer – Shoaib Munir May 22 '19 at 6:19
  • Need to pass in load: $cat_id = 26,28; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory'); $category = $categoryFactory->create()->load($cat_id); In this: ----------- $categoryProducts = $category->getProductCollection()->addAttributeToSelect('*')->addAttributeToSort('position', 'ASC')->addAttributeToFilter('color', array('in',$colorvalues)); – Shomita May 22 '19 at 7:13
  • Magento wont allow to load two category at a time, you can add category filter for multiple categories but you can't load with multiple categories – Shoaib Munir May 22 '19 at 7:29
  • Can you please update my code? – Shomita May 22 '19 at 7:35

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.