Magento apply sort order for the search criteria interface repository by using Magento\Framework\Api\SortOrderBuilder Class.
You can do sorting by ASC or DESC order by any field type for a given search criteria repository.
$sortOrder = $this->sortOrderBuilder ->setField('created_at') //FIELD_NAME ->setDirection(SortOrder::SORT_DESC) // SORT_TYPE ->create();
You can check the given code snippet to fetch orders by created date with the search criteria builder order repository.
<?php namespace Rbj\Sales\Model; use Magento\Framework\Api\SortOrder; use Magento\Framework\Api\SortOrderBuilder; use Magento\Framework\Api\SearchCriteriaBuilderFactory; use Magento\Sales\Api\Data\OrderSearchResultInterface; use Magento\Sales\Api\OrderRepositoryInterface; class SortBySalesOrder { public function __construct( private SortOrderBuilder $sortOrderBuilder, private OrderRepositoryInterface $orderRepository, private SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory ) { } public function getOrdersByCreatedDate(): OrderSearchResultInterface { $searchCriteriaBuilder = $this->searchCriteriaBuilderFactory->create(); $searchCriteriaBuilder->addFilter('state', ['new', 'pending_payment'],'in'); $sortOrder = $this->sortOrderBuilder ->setField('created_at') ->setDirection(SortOrder::SORT_DESC) ->create(); $searchCriteriaBuilder->addSortOrder($sortOrder); $searchCriteria = $searchCriteriaBuilder->create(); return $this->orderRepository->getList($searchCriteria); } }
You can check the above class, We have applied for sort order on the order search criteria repository to fetch all the results by created date.