Tuesday 4 February 2014

Add Limit To Collection Size in Magento



Magento : Add Limit To Collection Size

Sometimes you need to get a collection of objects from Magento but only want to limit them to a certain number. This is especially useful if your collection is going to be in the hundreds of thousands – as you do not want to be performing complex operations on a collection of that size.

A collection is a Model type containing other Models, it is basically used in Magento to handle product lists (ie. from a category or a bundle option), but not only.

Following are some of the best ways to limit your collection size:
setPageSize()

This function will limit the number of results that are returned – basically using a LIMIT X mysql query. For example:

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->setPageSize(10);
echo $collection->count(); // will echo 10

setPage()

setPage() is similar to using setPageSize but you can add two parameters – just like you would with mysql LIMIT 10,5 for example. The first parameter being the start from point – the next being how many you wish to bring back:      

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->setPage(0,20); // will bring back the first 20 products
$collection->setPage(10,5); // will bring back 5 products after the 10th product

getSelect()->limit()

This function allows you to add your own limit to the select query – it’s basically the same as entering LIMIT X. For example: 

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->limit(20); // will bring back our first 20 results 

A handy hint to see what these limits are doing to your mysql query is to echo out your mysql query in the code. To do this you can simply perform the following after you’ve tweaked your $collection object:

           echo $collection->load()->getSelect(); // will echo out our mysql query
Let me know in the comments if this has helped you........... Enjoy........Happy coding :)...

Magento : Get Store Id/Website Id



After hours of huffing and puffing i was able to figure out a way to get the store information programmatically :)

Get current store:

      Mage::app()->getStore();

Get current store Id:

      Mage::app()->getStore()->getId();


Get current website Id:


$storeId = Mage::app()->getStore()->getId();
Mage::getModel('core/store')->load( $storeId )->getWebsiteId();

Get store info by store code:

            $storeCode = "your_store_code";

Mage::getModel( "core/store" )->load( $storeCode );

Get website info by website code:

            $websiteCode = "your_website_code";

Mage::getModel( "core/website" )->load( $websiteCode );

Get all stores:

            Mage::app()->getStores();

Let me know in the comments if this has helped you........... Enjoy........Happy coding :)....