9

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');
  • Did you try this $giftColletion->setPageSize(3) – Magento 2 Nov 10 '16 at 5:05
  • Will try it, It will result me 3 records, right? – Nitin Pawar Nov 10 '16 at 5:08
  • Yes you need to set count – Magento 2 Nov 10 '16 at 5:14
8

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);
  • You can change here 10 to your limit in setpagesize field. please let me know if you have any issue – Rakesh Jesadiya Nov 10 '16 at 5:18
  • how can i set order for two data fields like position and salary. – Nitin Pawar Nov 10 '16 at 5:32
  • you can use two times setOrder() – Rakesh Jesadiya Nov 10 '16 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. – Rakesh Jesadiya Nov 10 '16 at 5:36
  • 1
    HIIII ITS working now=>>> $collection->getSelect()->having('distance < '.$redious)->order('distance ASC')->limit($pageSize, $page); – Birjitsinh Zala Mar 1 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);
2
$giftColletion = $this->_giftFactory->getCollection()->addFieldToFilter('store_id', 1);
$giftColletion->setOrder('position', 'ASC');
$giftColletion->setOrder('attribute_code', 'ASC'); 
$giftColletion->setPageSize($limitNo);
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, privacy policy and cookie policy

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