10

I am using following code to filter result and i want to limit the result.

$giftColletion = $this->_giftFactory->getCollection();
$giftColletion->addFieldToFilter('store_id', 1);
$giftColletion->setOrder('position','ASC');
3
  • Did you try this $giftColletion->setPageSize(3)
    – Magento 2
    Commented Nov 10, 2016 at 5:05
  • Will try it, It will result me 3 records, right? Commented Nov 10, 2016 at 5:08
  • Yes you need to set count
    – Magento 2
    Commented Nov 10, 2016 at 5:14

6 Answers 6

10

You can use setPageSize() to use limit in collection

$giftColletion = $this->_giftFactory->getCollection();
$giftColletion->addFieldToFilter('store_id', 1);
$giftColletion->setOrder('position','ASC');
$giftColletion->setOrder('salary','ASC');
$giftColletion->setPageSize(10);
8
  • You can change here 10 to your limit in setpagesize field. please let me know if you have any issue Commented Nov 10, 2016 at 5:18
  • how can i set order for two data fields like position and salary. Commented Nov 10, 2016 at 5:32
  • you can use two times setOrder() Commented Nov 10, 2016 at 5:35
  • you can also try with $giftCollection->setOrder(array('position', 'salary'), asc) if both are in asc order. Above is used for different sort order. Commented Nov 10, 2016 at 5:36
  • 1
    HIIII ITS working now=>>> $collection->getSelect()->having('distance < '.$redious)->order('distance ASC')->limit($pageSize, $page); Commented Mar 1, 2019 at 13:25
2

Using Page size you can set limit:

$giftColletion = $this->_giftFactory->getCollection();
    $giftColletion->addFieldToFilter('store_id', 1);
    $giftColletion->setOrder('position','ASC');
    $giftColletion->setPageSize($pageSize);
    $giftColletion->setCurPage($page);
0
2
$giftColletion = $this->_giftFactory->getCollection()->addFieldToFilter('store_id', 1);
$giftColletion->setOrder('position', 'ASC');
$giftColletion->setOrder('attribute_code', 'ASC'); 
$giftColletion->setPageSize($limitNo);
1
  • I am looking for fetch product as per attribute value 1,2,3,4 not is ASC. Commented Nov 26, 2020 at 6:50
2

I normally use the following but setPageSize() is also valid:

$collection->getSelect()->limit($limit);

Regarding sorting, if the direction of your sorting is the same for all fields, you can set that in just one call using an array:

$collection->setOrder([$field1, $field2, ...], $dir);
1

Order by :

$giftColletion->setOrder('position','ASC');
$giftColletion->setOrder('store_id','ASC');
1

You can use below code.

$giftColletion = $this->_giftFactory->getCollection();
$giftColletion->addFieldToFilter('store_id', 1)->setPageSize($limit)->setCurPage($criteria)->setOrder('position','ASC');

Your Answer

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

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