Magento – Fetch Value from Collection Without Foreach Loop

collection-filteringcollection;performance

I have a custom collection

$someCollection = Mage::getModel('mymodule/mymodel')->getCollection()
                           ->addFieldToSelect('some_field')
                           ->addFieldToFilter('another_field', array('eq' => $someValue));

Now consider, that this collection will always return only one row from the table, i.e.

$someCollection->getSize();

will always be "1". How to get the value of "some_field" without a foreach like:

foreach($someCollection as $row){
    $catchTheValue = $row->getSomeField();
}

I don't want to write foreach loop for one iteration. Can someone help?

Best Answer

If you know that the collection just has one item then you could simply use $someCollection->getFirstItem(). This will give you the first and in your case only item. You can then continue to use the getSomeField() etc on this object.

A second option is possible to use ->load($attribute_value, 'attribute_code'); on the object but this can add overhead if the table is of a large size.

Related Topic