3

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

6

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))
3

Here you can see a protected question about this showing how to perform what you need.

Basically using

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
    array('attribute'=>'orig_price','gt'=>'100'),
));

should do the trick.

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .