Question

Is it possible to have a random sort when searching with repositories? Checked dev docs and unsure. Not found much elsewhere.

https://devdocs.magento.com/guides/v2.3/extension-dev-guide/searching-with-repositories.html#sorting

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\Api\SortOrderFactory;
$this->searchCriteriaBuilder->addFilter(MessageInterface::STATUS, [Data::ENABLED], 'eq');
$randomSort = $this->sortOrderFactory
    ->create()
    ->setField(MessageInterface::SORT)
    ->setDirection(SortOrder::SORT_ASC); // random sort here
$this->searchCriteriaBuilder->setSortOrders([$randomSort]);
$searchCriteria = $this->searchCriteriaBuilder->create();
return $this->messageRepositoryInterface->getList($searchCriteria)->getItems();
Was it helpful?

Solution 2

Got a solution.

$result = $this->messageRepositoryInterface->getList($searchCriteria)->getItems();
if ($group->getSortby() == Data::RANDOM) {
    shuffle($result);
    return $result;
}
return $result;

OTHER TIPS

You can use the built-in method array_rand to get either SORT_ASC or SORT_DESC. Something like this:

$this->searchCriteriaBuilder->addFilter(MessageInterface::STATUS, [Data::ENABLED], 'eq');

$directions = [SortOrder::SORT_ASC, SortOrder::SORT_DESC];
$randomDirection = $directions[array_rand($directions)];

$randomSort = $this->sortOrderFactory
    ->create()
    ->setField(MessageInterface::SORT)
    ->setDirection(randomDirection); // random sort here
$this->searchCriteriaBuilder->setSortOrders([$randomSort]);
$searchCriteria = $this->searchCriteriaBuilder->create();
return $this->messageRepositoryInterface->getList($searchCriteria)->getItems();

Missing feature but very difficult to implement

https://github.com/magento/magento2/issues/28315

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top