从Magento Collection获取数据

时间:2013-05-14 04:21:11

标签: php magento collections magic-function

我有一个包含一行数据的集合。如果我这样做,

$collection->getData();

它给我一个如下所示的数组,

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

但当我$collection->getField1()时,它会显示Undefined Method。据我所知,php magic getter应该像这样工作。不是吗?

任何想法如何在没有foreach构造的情况下获得此值。

1 个答案:

答案 0 :(得分:11)

魔术getter和setter方法仅适用于从Varien_Object继承的Magento对象。在模型和块的实践中。集合既不是模型也不是块。集合是一个foreach能够包含0 - N个模型对象的对象。

集合的getData方法将返回集合中每个模型的原始PHP数组。

#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;
}

您可能想要做的是从集合中获取第一个模型,然后获取其数据。

$data = $collection->getFirstItem()->getData();
$field1 = $collection->getFirstItem()->getField1();
相关问题