How to sort & limit a collection in Magento?

We can sort & set limit to a collection in Magento.
Please refer the below example for better understanding.

For Example:
$collection = Mage::getModel('news/news')->getCollection();
$collection->>addAttributeToFilter('store_id', $storeId);

$collection->setOrder('news_id','ASC');
$collection->setOrder('update_time','DESC');
$collection->setPageSize(5);
$collection->count();

Description:
Step 1: We have created a "news" model collection i.e ($collection).
Step2: Filtering the collection by "store_id".
Step3: Sorting the collection by "news_id" in Ascending order.
Step4: Sorting the collection by "update_time" in Descending order.
Step5: Set limit of 5 records on collection.
Step6: Forces the collection to load.

Output Query like below:

SELECT `main_table`.* FROM `news` AS `main_table` WHERE (store_id = '1')
ORDER BY news_id ASC, update_time DESC, news_id  ASC, update_time DESC LIMIT 5


How to sort & limit a collection in Magento? How to sort & limit a collection in Magento? Reviewed by Web Technology Funda on 12:38:00 AM Rating: 5

1 comment

  1. thanks for this info and you can find more info on this link:
    http://www.creare.co.uk/limiting-collection-size-in-magento

    ReplyDelete

Free! Free!Free! Subscribe to Get Free PHP (Magento) tutorial Update in Your Inbox!!! Hurry Up!!!