Magento 2: Sort order and limit product collection

  • 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()
  • 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()
        ->setPageSize(10) // only get 10 products 
        ->setCurPage(1)  // first page (means limit 0,10)

    You have not answered the limit part.

    @Hashid updated the answer.

    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

    setPageSize is not working for me

    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)`

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM