5

Having read Fixing Magento Flat Collections with Chaos by Alan Storm and finding a similar SO question here I am trying to return products that are in a category but without using Magento's "flat" data.

Here is the code that I originally used:

        $category_model = Mage::getModel('catalog/category')->load($cid);
        $collection = Mage::getModel('catalog/product_collection');
        $collection->addCategoryFilter($category_model);
        $collection->addAttributeToSort('entity_id','DESC'); 
        $collection->addAttributeToSelect('*');

        $collection->printLogQuery(true);

When this code gets fired through AJAX I get different results than when I run it from an observer and the reason is because of flat data. So I have written my own classes that are meant to use the EAV model:

app/code/local/Mynamespace/Mymodule/Model/Category.php:

class Mynamespace_Mymodule_Model_Category extends Mage_Catalog_Model_Category
{
    protected function _construct()
    {

        $this->_init('catalog/category');

    }

}

And:

app/code/local/Mynamespace/Mymodule/Model/Productcollection.php:

class Mynamespace_Mymodule_Model_Productcollection 
extends Mage_Catalog_Model_Resource_Product_Collection
{
    protected function _construct()
    {

        $this->_init('catalog/product');
        $this->_initTables();
    }

}

And then change my query code:

        $category_model = Mage::getModel('mymodule/category')->load($cid);
        $collection = Mage::getModel('mymodule/productcollection');
        $collection->addCategoryFilter($category_model);
        $collection->addAttributeToSort('entity_id','DESC'); 
        $collection->addAttributeToSelect('*');

        $collection->printLogQuery(true);

However the above code is still querying the flat data table. What is it I may be doing wrong?

Community
  • 1
  • 1
beingalex
  • 2,416
  • 4
  • 32
  • 71

2 Answers2

3

since you already rewrote Mage_Catalog_Model_Resource_Product_Collection simple rewrite

public function isEnabledFlat()
{
    if (Mage::app()->getStore()->isAdmin()) {
        return false;
    }
    if (!isset($this->_flatEnabled[$this->getStoreId()])) {
        $this->_flatEnabled[$this->getStoreId()] = $this->getFlatHelper()
            ->isEnabled($this->getStoreId());
    }
    return $this->_flatEnabled[$this->getStoreId()];
}

to

public function isEnabledFlat()
{
    return false;
}

that should fix it :)

Justus Krapp
  • 1,116
  • 9
  • 10
2

To disable flat index for the current request, you can also set the configuration temporarily without saving it as described here:

Mage::app()->getStore()->setConfig(
    Mage_Catalog_Helper_Product_Flat::XML_PATH_USE_PRODUCT_FLAT, '0');

It is important that this is done before the product collection has been initialized because that's where the configuration is checked (via isEnabledFlat().

Community
  • 1
  • 1
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111