質問

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?

役に立ちましたか?

解決

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.

他のヒント

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.

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.

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

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.

ライセンス: CC-BY-SA帰属
所属していません magento.stackexchange
scroll top