Getting data from a Magento Collection

Thanu picture Thanu · May 14, 2013 · Viewed 17.9k times · Source

I have a collection that has one row of data in it. If I do following,

$collection->getData();

it give me an array like below,

  array(1) {
    [0] => array(3) {
       ["id"] => string(1) "1"
       ["field1"] => string(10) "Field 1 Data"
       ["field2"] => string(10) "Field 2 Data"
    }
  }

But when I do $collection->getField1() it says Undefined Method. As far as I know php magic getter should work like this. Isnt it?

Any Ideas how to get this value without a foreach construct.

Answer

Alan Storm picture Alan Storm · May 14, 2013

The magic getter and setter methods only apply to Magento objects that inherit from Varien_Object. In practices that's Models, and Blocks. A collection is neither a model or a block. A collection is a foreachable object that contains 0 - N model objects.

A collection's getData method will return the raw PHP array of each model in the collection.

#File: lib/Varien/Data/Collection/Db.php
public function getData()
{
    if ($this->_data === null) {
        $this->_renderFilters()
             ->_renderOrders()
             ->_renderLimit();
        $this->_data = $this->_fetchAll($this->_select);
        $this->_afterLoadData();
    }
    return $this->_data;
}

What you probably want to do is grab the first model from the collection, and then grab its data.

$data = $collection->getFirstItem()->getData();
$field1 = $collection->getFirstItem()->getField1();