5

I have a custom product attribute test_id which is a text field. I want to get all the values assigned to this attribute within a given product collection.

I found the following way of doing it. But I need to know if there is a better solution.

public function getAllTestIds() {
    $allValues = array();
    $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
    foreach($collection as $product) {
        $data = $product->getData();
        if(trim($data['test_id']) != '') {
            $allValues[] = $data['test_id'];
       }
   }
return $allValues;
}

2 Answers 2

5

@Sukeshini,add groupByAttribute() to get data of unique data and remove null .

public function getAllTestIds() {
    $allValues = array();
    $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('test_id', array(
    'notnull' => true,
    ))->groupByAttribute('test_id');

    foreach($collection as $product) {
        $data = $product->getData();
            $allValues[] = $data['test_id'];
       }
   }
return $allValues;
}
0
2

A simpler way is:

public function getAllTestIds() {
    $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('test_id');
    return $collection->getColumnValues('test_id');
}

Only selecting the attribute(s) we are interested in, improves collection loading performance. But getColumnValues() calls load(), so it is still not optimized much.

If you want to avoid loading the whole collection, a hand crafted SQL query is probably necessary.

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.