I have a custom attribute for product called warehouse
of type drop down.
In order to load the Sku => Warehouse
(get assigned value for each product) updates between dates via models; I do the following:
// Load warehouse attribute options
$warehouse_options = array();
$options = array();
$attribute = Mage::getSingleton('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'warehouse');
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
}
$attribute = null;
foreach ($options as $option) {
$warehouse_options[$option['value']] = $option['label'];
}
$options = null;
// Load all products updated since last sync
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('updated_at', array(
'from' => $datetime_from,
'to' => $datetime_to,
'date' => true
));
// Init results
$results = array(
'ServerDateTime' => $datetime_now,
'Mapping' => array()
);
// Build results
foreach ($collection as $p) {
$product = Mage::getModel('catalog/product')->load($p->getId());
$results['Mapping'][] = array(
'Sku' => $product->getSku(),
'Warehouse' => isset($warehouse_options[$product->getWarehouse()]) ? $warehouse_options[$product->getWarehouse()] : ''
);
$product = null;
}
$collection = null;
This works, but quite slow as each product is getting loaded, so if I had 3000
products, thats 3000+
queries.
Is there a way to optimise this so I can load the desired data with minimal amount of query & processing?
I have tried to use just the collection like this using addAttributeToSelect
:
$collection->addAttributeToSelect('sku', 'warehouse');
However, the returned $collection->getData()
does not contain the field warehouse
. Here's an example response array:
Array
(
[0] => Array
(
[status] => 1
[entity_id] => 4
[type_id] => simple
[attribute_set_id] => 4
[updated_at] => 2015-07-07 15:35:35
[sku] => C13S041061
)