I have a class that returns 3 products from a category, these products are ordered by entity id and always returns the same 3 products from category X. I want to randomise them. in magento 1 you could do something like $collection->getSelect()->order('RAND()');
, but this does not work in magento 2 anymore.
This is code that gets 3 products from category X.
protected $categoryFactory;
public function __construct(
\Magento\Catalog\Model\CategoryFactory $categoryFactory
)
{
$this->categoryFactory = $categoryFactory;
}
public function getCategory($id)
{
$category = $this->categoryFactory->create()->load($id);
return $category;
}
public function getProductsCollection($id)
{
$r = array();
$products = $this
->getCategory($id)
->getProductCollection()
->addAttributeToSelect('*')
->setPageSize(3)
->getItems();
foreach ($products as $product) {
$r[] = $product->getData();
}
return $r;
}
Best Answer
I suggest you use the
orderRand()
method.You can do: