Rand sort on searchCriteria getItems
-
14-04-2021 - |
Domanda
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();
Soluzione 2
Got a solution.
$result = $this->messageRepositoryInterface->getList($searchCriteria)->getItems();
if ($group->getSortby() == Data::RANDOM) {
shuffle($result);
return $result;
}
return $result;
Altri suggerimenti
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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange