TransWikia.com

Fetch value from collection without foreach loop

Magento Asked by Shathish on December 27, 2020

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?

5 Answers

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.

Correct answer by David Manners on December 27, 2020

You can do something like this:

$someFieldList = array_map(function($item){
  return $item['some_field'];
}, $collection->toArray(['some_field'])['items']);

You can pass the list of fields to return as array to the toArray function.

Answered by Shankar Thyagarajan on December 27, 2020

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.

Answered by Fabian Schmengler on December 27, 2020

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

Answered by Sudhir on December 27, 2020

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.

Answered by Fabian Blechschmidt on December 27, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP