Magento 1.9 – Get Product Collection Filtered by Attribute Existence

attributescollection-filteringmagento-1.9product-attributeproduct-collection

Goal: Retrieve a collection of products that have a certain attribute

Here's what I'm trying:

public function Hydrate($attribute)
{
    $this->id = Mage::helper('myHelper')->CamelCase($attribute->getFrontendLabel());
    $this->name = $attribute->getFrontendLabel();

    $products = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToSelect('*')
        ->addFieldToFilter($attribute->getAttributeCode(),array('like' => '%%'))
        ->load();

    foreach ($products as $product)
    {
        array_push($this->collection,Mage::getModel('myModels/Json_Product')->Hydrate($product));
    }



    return Mage::helper('myHelper')->ConvertToJson($this);
}

It's working. However, I was just wondering if that addFieldToFilter() is going to have any repercussions that I can't currently see?

Magento 1.9.x

Best Answer

LIKE is not the most performant choice. Since %% (which is equivalent to %) matches every string, even empty strings, you probably want to check if the field is NOT NULL.

The right filter parameter in this case is:

    ->addFieldToFilter($attribute->getAttributeCode(),array('notnull' => true))