0

In Magento 2.3.3, How Can I Filter Product Collection by Multiple Attributes? First attribute SKU needs to check using "IN" second attribute is yes/no value. I need to filter collection by SKU array OR custom_attribute. I have tried few things but it did not return expected results.

$collection = $layer->getProductCollection()->addAttributeToFilter(
    array(
        array("attribute"=>"sku",array('in' => $skus)),
        array("attribute"=>"universal_fitment","eq"=>1)
    )
);
0

Please try below.

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$productCollection->addAttributeToSelect('*');
$queryp = 'product'; 
$querys  = 'product';
$productCollection->addAttributeToFilter(
      [
       ['attribute' => 'sku', 'in' => array('Product 1','Product 2')],
       ['attribute' => 'custom_atribute', 'in' => array('5,4')]
      ]);

$collection = $productCollection->load();

foreach ($collection as $product){
     echo 'Name  =  '.$product->getName().'<br>';
}  

?>

and other case

<?php 

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$products = $objectManager->get('Magento\Catalog\Model\Product')
            ->getCollection()
            //->addAttributeToFilter('is_old',1)
            ->addAttributeToFilter('sku',array('Product 1','Product 2'))
            ->addAttributeToFilter('custom_atribute', array('in' => '5,4'));

echo "<pre>";
print_r($products->getData());

?>

Hope it works!

| improve this answer | |
  • Won't this filter work like AND operator? – Nayem323 Jan 17 at 4:48
  • just tell me which attribute you want and tell me cases so I can do as per that. – sarvesh Dineshkumar Patel Jan 17 at 4:49
  • I have an array of sku. I only want those products that are exist in that array with those products that have a custom attribute value. Imagine i have 10 products (1-10 sku) in which 6 and 8 have an custom attribute value. Now i have 1,2,3,4,5 sku in an array so i want products 1-5 and 6,8 by filtering collection. – Nayem323 Jan 17 at 4:54
  • ok, I can understand but maybe SKU multiple checks you need a custom query. let me try. – sarvesh Dineshkumar Patel Jan 17 at 4:58
  • @Nayem updated answer please check it – sarvesh Dineshkumar Patel Jan 17 at 5:16

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.