addAttributeToSelect for multiple fields not working

Use addFieldToSelect incase of addAttributeToSelect

addFieldToSelect used for flat model

addAttributeToSelect user for EAV model


The reason that you are getting the error is that the method Mage_Sales_Model_Resource_Collection_Abstract::addAttributeToSelect only works for individual attributes and not an array of attributes.

It only works for individual attributes because it will validate call to make sure the attribute is real.

public function addAttributeToSelect($attribute)
{
    $this->addFieldToSelect($this->_attributeToField($attribute));
    return $this;
}

When you look into Mage_Sales_Model_Resource_Collection_Abstract::_attributeToField you see that it works as follows.

  1. If you pass a string then it will simply return the string,
  2. If you pass an object then it will validate that this is an object of type Mage_Eav_Model_Entity_Attribute and return the attribute code,

The code looks as follows:

protected function _attributeToField($attribute)
{
    $field = false;
    if (is_string($attribute)) {
        $field = $attribute;
    } elseif ($attribute instanceof Mage_Eav_Model_Entity_Attribute) {
        $field = $attribute->getAttributeCode();
    }
    if (!$field) {
        Mage::throwException(Mage::helper('sales')->__('Cannot determine the field name.'));
    }
    return $field;
}

So you options are the following as I see it:

  1. Simply call addFieldToSelect with an array of attribute codes. Since you are only passing codes and not objects you will not get the validation, but maybe you do not need this in your case.
  2. Call addAttributeToSelect once for each attribute.

I would suggest in your case option one would be the best.


AFAIK a work around is just to do them all singularly (for whatever reason you are determined to use addAttributeToSelect:

->addAttributeToSelect('created_at') 
->addAttributeToSelect('customer_id') 
->addAttributeToSelect('increment_id') 
->addAttributeToSelect('updated_at') 
->addAttributeToSelect('status') 
->addAttributeToSelect('entity_id')
->addAttributeToSelect('state')