3

I am trying to filter product, I having a list of product ids in an array and i want to filter product base on this ids.

I want to fetch all the product which does not have this ids (Not In) How can i write it. Here is my code.

 $ruleCreateArr = [10,15,21];

 $collection = $this->productCollectionFactory->create();

 $collection->addAttributeToSelect(array('name','id'))
           ->addAttributeToFilter('entity_id', array('nin', $ruleCreateArr));

It seems the "nin" filter not working.

2

You can try the following its working for me:

$ruleCreateArr = array(10,15,21);

$collection = $this->productCollectionFactory->create();

$collection->addAttributeToSelect(array('name','id'))
           ->addAttributeToFilter('entity_id', array('nin', $ruleCreateArr));
0

This will work. The problem is that you have a comma separating your operator and negated values. It should be ['nin' => $ruleCreateArr] instead of array('nin', $ruleCreateArr).

$ruleCreateArr = [10,15,21];

$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('name');
$collection->addAttributeToFilter('entity_id', ['nin' => $ruleCreateArr]);

Also, to ensure that you remain within Magento's published coding standards for Magento 2, be sure to use short array syntax. [] vs. array()

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.