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

    foreach ($products as $product) {
        $r[] = $product->getData();
    return $r;

I suggest you use the orderRand() method.

You can do:

$productsCol = $this


$products = $productsCol->getItems();

There is a problem in your code: $collection->getSelect()->order('RAND()');

you have called php RAND() inside the quote('RAND()') which is invalid.

remove the quote for RAND()

your code itself should work, also put min & max length RAND($min, $max)

But still I would recommend you to go with Magento way (same as Raphael answer)

  • it is in quotes, because it is SQL expression... – pankijs Apr 28 '16 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.