0

I am trying to filter product collection by ids if I use below code, the filter works ok and the product shows.

$this->_productCollection
            ->addFieldToFilter('entity_id',array('in'=> 460 ));

The problem is that if I set an array to this code and try to filter, I keep getting empty collection.

$getData = array(460);
$this->_productCollection
            ->addFieldToFilter('entity_id',array('in'=> $getData ));

I've already tried setting array like the following

$getData[$a]= array(460);

and reading like

array('in'=> $getData[$a] )

PS: My array is variable, not only one product I can't see anything wrong with the code and if dump array it is ok I think: array([0] => int(460))

5
  • Well, I was placing the code below this: $this->prepareSortableFieldsByCategory($layer->getCurrentCategory()); if ($origCategory) { $layer->setCurrentCategory($origCategory); } } after placing the code before this lines it works weirdly, if someone can explain, I will accept as answer.
    – Gabriel G
    Commented May 16, 2018 at 15:01
  • Please share your full collection code. Are you having this on Magento 2?
    – kunj
    Commented May 16, 2018 at 18:27
  • Please check that 460 is product's ID or category's ID.
    – kunj
    Commented May 17, 2018 at 5:20
  • It is product ID, and on magento 1.9.3. Please check my comment, any info?
    – Gabriel G
    Commented May 17, 2018 at 19:56
  • Ok, try my code and let me know if it is working for you or not.
    – kunj
    Commented May 17, 2018 at 20:12

2 Answers 2

0

Try this:

$getData= array(17,78);
$collection->addAttributeToFilter('entity_id',array('in'=> $getData ));

This is working for me.

0

You were doing the filter after category filter,so it may be that product is not in current category.That why your collection was returning Null. .

Better way to filter by product ids is

$productIDS =  array(460,4,98);
$collection->addIdFilter($productIDS);
1
  • the products are in the category. it is like the code was not accepting an array of values after those lines of code. Check my comment.
    – Gabriel G
    Commented May 17, 2018 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.