5

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?

8

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.

  • 2
    the second approach loads a complete model and initilizes it. I think what he wants is to avoid the overhead – Fabian Blechschmidt Nov 16 '13 at 9:30
  • @FabianBlechschmidt true I always have the gut feeling that loading the collection would take more overhead, but forget that it is often the case. – David Manners Nov 16 '13 at 9:32
  • @FabianBlechschmidt: You're right that's a big table, I don't wanna load all the value instead only one column, so I don't want to use load(). – Shathish Nov 16 '13 at 9:35
  • @Shathish Then I would use the first option. – David Manners Nov 16 '13 at 9:41
4

I checked the Mage_Core_Model_Resource_Db_Abstract and Mage_Core_Model_Resource_Db_Collection_Abstract for any method that does this and there is none.

I think implementing your own ResourceModel is the best way. Just shot directly a query to the database and return the value.

  • yes I already thought about that, I'll do that in the next version of my module. Thanks! – Shathish Nov 16 '13 at 9:56
1

You could make use of the underlying Zend_Db_Select object and execute it manually, bypassing the Magento model entirely:

$someFieldValue = $collection->getConnection()
     ->query($collection->getSelect())
     ->fetchColumn();

fetchColumn() returns the raw value of the first column returned by the query.

Note that this will only work if you don't rely on any Magento events or special attribute models.

0

There is this one method getAllIds() in Mage_Core_Model_Resource_Db_Collection_Abstract. It return an array containing primary key of all rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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