Question

The task is trivial. I need to get list of products for particular store view with a flat catalog enabled. The most obvious solution is the following:

$collection = Mage::getResourceModel('catalog/product_collection')
    ->setStore($storeId);

In fact setStore() method is not making any difference here because it is called after the _initSelect() method of Mage_Catalog_Model_Resource_Product_Collection which gets the name of the flat table based on store ID. As the store ID is not yet set it takes the current store ID.

So the obvious workaround would be to set a current store ID before getting a model.

Mage::app()->setCurrentStore($storeId);

$collection = Mage::getResourceModel('catalog/product_collection');

It will work. But only if you need to get a collection once. If you need to get a collection in the loop or you just need two back to back collections you will not be able to set a specific store for them.

The reason is that Mage_Catalog_Model_Resource_Product_Flat class has it's own _storeId property and in the constructor it is set to the current store ID. That's why it will be set first time. Then for some reason (heaven knows I hope there is one) in Mage_Eav_Model_Entity_Collection_Abstract::_init each resource module is fetched as a singleton. So no constructor for 2nd call.

This all looks so wrong that I'm pretty sure I'm wrong and it is not another Magento bug (or two). Hope somebody can shed a light on it.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top