Getting data from a Magento Collection

17,818

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();
Share:
17,818
Thanu
Author by

Thanu

Scrum Master (CSM) / Senior Web Developer

Updated on June 05, 2022

Comments

  • Thanu
    Thanu almost 2 years

    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.

  • AbdulBasit
    AbdulBasit over 8 years
    $data = $collection->getFirstItem()->getData(); is what I was looking for. Thanks