1

I want to get all items from the product compare list, but only for a certain visitor. This is what I tried:

$_productCollection = Mage::helper('catalog/product_compare')->getItemCollection();
$test = $_productCollection->addFieldToFilter('visitor_id', 2)->getItems();

This should return nothing, because in my catalog_compare_item table is no row for visitor_id 2. But it returns everything no matter if I use a filter or not. Whats the correct way of doing that?

Thanks!

8
  • 2
    comment out the ->getItems() part and complete your code with: $_productCollection->count(); echo $_productCollection->getSelect()->__toString(); and see what's happening in the SQL query, it might lead you to the solution Commented Apr 30, 2014 at 14:10
  • I debugged and got the SQL. When I run it in my SQL editor, it returns nothing (which is right), but the code still has 1 result (checked with count). What could be the reason? Commented Apr 30, 2014 at 14:19
  • so when you run the SQL by itself, it gives you no result, at all ? and when you echo the $_productCollection->count() it gives you 1? That is some weird stuff. What is you loop through the getItems() ? Is there something out of the ordinary in what it gives you? Commented Apr 30, 2014 at 14:36
  • Yes, exactly, the SQL seems to be right, the code not. Looping through the collection gives me the one product for visitor_id 1, which is not what I expect when I pass 2 to addFieldToFilter. This is my code now: $collection = Mage::helper('catalog/product_compare')->getItemCollection(); $collection->addFieldToFilter('visitor_id', 2); $sql = $collection->getSelect()->__toString(); $count = $collection->count(); foreach($collection as $product) { $id = $product->getId(); // thats the id from the product with visitor_id 1 } Commented Apr 30, 2014 at 14:39
  • I tried using getSize() instead of count() and it returns either 0 or 1, which is correct. But still, the foreach iterates one time, which is wrong. Commented Apr 30, 2014 at 14:58

1 Answer 1

3

Not completely sure what you are wanting to do but the following should work well to loop through the items.

$_productCollection = Mage::helper('catalog/product_compare')->getItemCollection();
foreach ($_productCollection as $product) {
    echo $product->getName();
}

You can note that the Mage::helper('catalog/product_compare')->getItemCollection() will already add a filter for the visitor/customer so you should not have to add this filter.

If you are wanting to loop through another user's items that I would suggest not using this function but simply building your own collection from:

Mage::getResourceModel('catalog/product_compare_item_collection')
    ->useProductItem(true)
    ->setStoreId(Mage::app()->getStore()->getId());

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.