Faster Loading of Media Images in Magento Product Collection

mediaproductproduct-collectionproduct-images

TL;DR: How do I load the product images/gallery without loading the whole product?

I want to load the images on a product. What I do in the .phtml

$_popularCollection = $this->getPopularCollection();
foreach ($_popularCollection as $_product):
    // the rest
    $mediaGallery = $_product->getMediaGalleryImages();
endforeach;
//the rest

What I do in the Block class:

public function getPopularCollection() {
    // http://magento.stackexchange.com/q/5838/3089

    // no category
    if ( is_null( $this->getCategoryId() ) )
        return false;

    /** @var Mage_Catalog_Model_Category $category */
    $category = Mage::getModel('catalog/category')->load( (int)$this->getCategoryId() );

    /** @var Mage_Catalog_Model_Resource_Product_Collection $_popularCollection */
    $_popularCollection = Mage::getModel('catalog/product')->getResourceCollection();
    $_popularCollection->addAttributeToSelect('*');
    $_popularCollection->setStoreId(Mage::app()->getStore()->getId());
    $_popularCollection->addCategoryFilter($category);

    return $_popularCollection;
}

This works But I load everything: $_popularCollection->addAttributeToSelect(*);

I tried $_popularCollection->addAttributeToSelect('media_gallery');
But it doesn't seem to work.

Best Answer

addAttributeToSelect('media_gallery') is not working as media_gallery will come from complicated logic.

You can get easy media_gallery data inside at loop by loading the full product model But it will take a lot of memory in this case.

Use Backend model of media_gallery attribute & afterload of product Model

For getting media_gallery attribute value without full product load (Mage::getModel('catalog/product')->load($ProductID)) .

You can use afterLoad(), using this function call backend model of media_gallery eav attribute load the media image. This is much faster than full model load(Mage::getModel('ctalog/product')->load($ProductID))

foreach($his->getPopularCollection() as $product){
    $attributes = $product->getTypeInstance(true)->getSetAttributes($product);
    $media_gallery = $attributes['media_gallery'];
    $backend = $media_gallery->getBackend();
    $backend->afterLoad($product); 
    $mediaGallery = $product->getMediaGalleryImages();
        /* get Image one by  using loop*/
        foreach ($product->getMediaGalleryImages() as $image) {
        echo ($image->getUrl());
        }     

echo "<br/>..........................................<br/>";


}