Custom resource model for Magento product flat tables

Custom resource model for Magento product flat tables

In this article we will try to explain how to create your own resource model for getting data from the product flat tables. First of all you need to know why we should do this. It’s simple. For example, you have a category page with configurable products and you need to get all attribute values on this page. Can anybody tell me how to do it and avoid using the following code snippet?

$product->getTypeInstance()->getConfigurableAttributesAsArray()

The previous example is not good, because it would make category page very slow and grab a ton of unneeded attributes.
We’ve found another way.
First, you should create your module, Magento geeks know how to do this, newbies can find this info in Google or in the our blog :)
Next step is creating the resource model file, we call it
app/code/local/Atwix/Mymodule/Model/Resource/Flat.php

Below you can see code of this file

<?php

class Atwix_Mymodule_Model_Resource_Flat extends Mage_Core_Model_Resource_Db_Abstract
{
    protected $_storeId;

    protected function _construct()
    {
        $this->_init('catalog/product_flat', 'entity_id');
        $this->_storeId = (int)Mage::app()->getStore()->getId();
    }

    public function getData($entityId)
    {
        $resource = Mage::getSingleton('core/resource');
        $select = $resource->getConnection('core_read')->select();
        $select
            ->from($this->getTable(array('catalog/product_flat', $this->_storeId)), '*')
            ->where('entity_id = :entity_id');

        $result = $resource->getConnection('core_read')->fetchAll($select, array('entity_id' => $entityId));

        return $result;
     }
}

We avoided using magento models or collections for getting data.
The method getData returns array with data selected from catalog_product_flat_n table, you can pass any conditions you want into the where() function. You can add join(), group(), etc.. methods to prepare and sort of your dataset.

What would you like to read in the next article? Please, post in the comments, any your ideas are warmly welcome.

Thanks and enjoy.

Clients

Smart Brands Choose Us.

From startups backed by Mark Cuban and Sir Richard Branson, to some of the biggest eCommerce operations in the world, Atwix helps our clients deliver unparalleled eСommerce experiences. We’re proud to work with the following companies: