Magento – Joining address fields to order

collection;ee-1.13sales

I am trying to export orders and address using the following code:

    $collection = Mage::getModel('sales/order')->getCollection();
    $collection->addFieldToFilter('store_id', 3);
    if (!$this->isAll()) {
        $collection->addFieldToFilter('updated_at', array('from' => date('Y-m-d', strtotime('-1 day'))));
        $collection->addFieldToFilter('updated_at', array('to' => date('Y-m-d')));
    }

    $addressCollection = Mage::getModel('customer/address')->getCollection()->addAttributeToSelect('*');
    $addressCollection->getSelect()->limit(1);
    $address = $addressCollection->getFirstItem();
    foreach ($address->getAttributes() as $attribute) {
        if (is_null($attribute->getAttributeID()) || is_null($attribute->getFrontendLabel()) || ($attribute->getFrontendLabel() == '')) {
            continue;
        }
        $collection->joinAttribute($attribute->getName() . '_billing', 'order_address/' . $attribute->getName(), 'billing_address_id', null, 'left');
        $collection->joinAttribute($attribute->getName() . '_shipping' , 'order_address/' . $attribute->getName(), 'shipping_address_id', null, 'left');
    }

    echo $collection->getSelect();

But my select does not contain the joined fields – the output is:

SELECT `main_table`.* FROM `sales_flat_order` AS `main_table` WHERE (store_id = '3') AND (updated_at >= '2014-04-15') AND (updated_at <= '2014-04-16')

Best Answer

The Mage_Sales_Model_Resource_Collection_Abstract::joinAttribute method of sales models is empty and thus without any effect:

/**
 * Backward compatibility with EAV collection
 *
 * @todo implement join functionality if necessary
 *
 * @param string $alias
 * @param string $attribute
 * @param string $bind
 * @param string $filter
 * @param string $joinType
 * @param int $storeId
 * @return Mage_Sales_Model_Resource_Collection_Abstract
 */
public function joinAttribute($alias, $attribute, $bind, $filter = null, $joinType = 'inner', $storeId = null)
{
    return $this;
}

Replace the second part with joins

    $shippingCols = array();
    $billingCols = array();
    foreach ($address->getAttributes() as $attribute) {
        if (is_null($attribute->getAttributeID()) || is_null($attribute->getFrontendLabel()) || ($attribute->getFrontendLabel() == '')) {
            continue;
        }
        $billingCols[] = 'bill_address.' . $attribute->getName() . ' as billing_' . $attribute->getName();
        $shippingCols[] = 'ship_address.' . $attribute->getName() . ' as shipping_' . $attribute->getName();
    }
    $collection->join(array('bill_address' => 'order_address'), 'main_table.billing_address_id = bill_address.entity_id', $billingCols);
    $collection->join(array('ship_address' => 'order_address'), 'main_table.shipping_address_id = ship_address.entity_id', $shippingCols);