21

I need to sort the product collection by ID order DESC and add limit to product collection. Here is my code:

$objectManager     = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection        = $productCollection->create()
    ->addAttributeToSelect('*')
    ->load();

1 Answer 1

43

Just add this code addAttributeToSort('entity_id', 'desc') to your collection.

As product follows EAV structure, you can use addAttributeToSort('attribute_code', 'sort_order')

For limiting a collection use setPageSize() and setCurPage() methods:

$collection = $productCollection->create()
    ->addAttributeToSelect('*');

$collection 
    ->setPageSize(10) // only get 10 products 
    ->setCurPage(1)  // first page (means limit 0,10)
    ->load(); 
5
  • 1
    You have not answered the limit part.
    – Hashid
    Feb 3, 2017 at 9:32
  • @Hashid updated the answer. Dec 19, 2017 at 14:12
  • Great! This also fixed an issue when having 2 collection blocks on a page, one of them paging, which broke the other collection which wasn't meant to be paging. The 'setCurPage' on the latter fixed this 🥳
    – 00-BBB
    Nov 29, 2019 at 13:54
  • setPageSize is not working for me Dec 26, 2019 at 10:55
  • 1
    If you add setPageSize and setCurPage it will make 2 queries instead of one. Firstly it will count how many rows there are, and then will make query with limit. This might negate any speedup from adding limit. To make only one query you need to use $collection->getSelect()->limit(3)
    – Volvox
    May 26, 2020 at 23:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.