Home > Software design >  Magento 1.9 using wrong flat table when getting productcollection from multiple stores
Magento 1.9 using wrong flat table when getting productcollection from multiple stores

Time:04-09

I have a Magento 1.9 installation with 4 stores (2 websites with 2 stores each). For an export I need to get all products by store.

So this is what I tried:

/** @var Mage_Core_Model_Store[] */
$stores = Mage::app()->getStores();

foreach ($stores as $store) {
    if (!$store->getIsActive()) {
        continue;
    }

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

    /** @var Mage_Catalog_Model_Resource_Product_Collection */
    $productCollection = Mage::getModel('catalog/product')->getCollection();
    $productCollection->setStore($store);
    $productCollection->addStoreFilter($store);
    $productCollection->addAttributeToSelect(['id']);
    // some more filters

    $productCollection->load();

    foreach ($productCollection->getItems() as $item) {
    // do some stuff
    }
}

I have catalog_product_flat tables enabled.

When I debug the query for my $productCollection I see that it is using the correct flat table for the first store, but afterwards it is always using the flat table of the store that ran before.

store 1 -> catalog_product_flat_1

store 2 -> catalog_product_flat_1

store 3 -> catalog_product_flat_2

store 4 -> catalog_product_flat_3

Btw: I noticed, that the setStore() and addStoreFilter() do not have any impact on the selected table.

Is there anything I am missing?

Thanks!

CodePudding user response:

Since I could not find the reason for this problem I found a workaround to solve this.

$resource = Mage::getResourceModel('catalog/product_flat');
$select = $resource->getReadConnection()
    ->select('entity_id')
    ->from(['table' => $resource->getMainTable()], 'entity_id')
    ->where('table.status = 1');
    // some more filters
            
$results = $resource->getReadConnection()->fetchAll($select);

This query is using the correct flat table and since I only need the product ids this works perfectly for me.

  • Related