use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Framework\Api\SortOrder; use Magento\Framework\ObjectManager\ConfigLoaderInterface;
class YourClass { /** * @var ProductRepositoryInterface */ protected $productRepository;
/**
* @var SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var ConfigLoaderInterface
*/
protected $configLoader;
public function __construct(
ProductRepositoryInterface $productRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
ConfigLoaderInterface $configLoader
) {
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->configLoader = $configLoader;
}
public function getRandomProductSkus()
{
// Create a random sort order
$sortOrder = new SortOrder();
$sortOrder->setField('rand'); // 'rand' is not a native Magento field; you'll need to create a custom attribute for random sorting.
// Set the random sort order in the search criteria
$this->searchCriteriaBuilder->addSortOrder($sortOrder);
// Build the search criteria
$searchCriteria = $this->searchCriteriaBuilder->create();
// Get the list of products
$productList = $this->productRepository->getList($searchCriteria);
// Extract SKUs from the products
$skus = [];
foreach ($productList->getItems() as $product) {
$skus[] = $product->getSku();
}
return $skus;
}
}
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\ObjectManager\ConfigLoaderInterface;
class YourClass
{
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var ConfigLoaderInterface
*/
protected $configLoader;
public function __construct(
ProductRepositoryInterface $productRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
ConfigLoaderInterface $configLoader
) {
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->configLoader = $configLoader;
}
public function getRandomProductSkus()
{
// Create a random sort order
$sortOrder = new SortOrder();
$sortOrder->setField('rand'); // 'rand' is not a native Magento field; you'll need to create a custom attribute for random sorting.
// Set the random sort order in the search criteria
$this->searchCriteriaBuilder->addSortOrder($sortOrder);
// Build the search criteria
$searchCriteria = $this->searchCriteriaBuilder->create();
// Get the list of products
$productList = $this->productRepository->getList($searchCriteria);
// Extract SKUs from the products
$skus = [];
foreach ($productList->getItems() as $product) {
$skus[] = $product->getSku();
}
return $skus;
}
}