I'm filtering a product collection by the custom attribute ean with the following code

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('ean');
$collection->addFieldToFilter('ean', '678678');

foreach ($collection as $product)
{
     Mage::Log('product found');
}

There is product with this ean but no product is found.

  • What was the problem? I don't think it was the addFieldToFilter, was it? – Fabian Blechschmidt Sep 11 '13 at 13:58
  • Actually I had a space in at the end of the ean. Remember to always but quotes around debug messages... – PiTheNumber Sep 11 '13 at 13:59
  • narf :-) Always the same... – Fabian Blechschmidt Sep 11 '13 at 14:00
up vote 10 down vote accepted

The methods addFieldToFilter() and addAttributeToFilter() are the same.

/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php:339
/**
 * Wrapper for compatibility with Varien_Data_Collection_Db
 *
 * @param mixed $attribute
 * @param mixed $condition
 */
public function addFieldToFilter($attribute, $condition = null)
{
    return $this->addAttributeToFilter($attribute, $condition);
}

I would try to remove the filter, then loop over the collection and check the values of ean. What query is fired?

Maybe some observer hooks into catalog_product_collection_load_before and the query is altered and filters are added?

Load the collection and then check echo (string)$collection->getSelect(). After(!) the ->load().

try and use

$collection->addAttributeToFilter('ean', '678678');

This post gives some nice pointers on using collections

Maybe this:

$collection->addFieldToFilter('ean', '678678');

should be:

$collection->addAttributeToFilter('ean', '678678');

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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