0

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
        )

1 Answer 1

2

Looks like in the example addAttributeToSelect is used incorrectly. This method has following signature:

addAttributeToSelect($attribute, $joinType = false)

Replace $collection->addAttributeToSelect('sku', 'warehouse'); with

$collection->addAttributeToSelect('sku')->addAttributeToSelect('warehouse');

2
  • I am afraid i am still NOT getting the warehouse value back. It only works if i explictly load the product via model.
    – Latheesan
    Commented Dec 14, 2015 at 16:33
  • Is this an EAV attribute? Commented Dec 14, 2015 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.