I am looking to create a custom product collection using specific product attributes as filters. The product collection I am getting has well over 100 products in which is fine but I need to find a way of choosing 5 products at random from the collection and then load them to display on a page. Has anyone developed anything similar to this or know the best way of implementing this?
Magento – How to Get 5 Random Product IDs from Product Collection
collection-filteringcollection;product-collectionproductsrandom
Best Answer
I found out that
ORDER BY RAND()
is very unperformant on a Magento collection because all data gets copied to a temp table, assigned a random number and then sorted without index. If we reduce the data to be copied to just the ID, it gets a lot faster (still not perfect because the slow sorting remains but OK for a small catalog like yours).For this, I made a modified version of
getAllIds()
:Then I could load the products by these random ids:
Simpler alternative
An alternative that also works well on small catalogs (<10000 products) is to load all ids and select the random IDs with PHP:
You can read a more in depth analysis and see some benchmarks in my blog: http://www.schmengler-se.de/en/2015/09/show-random-products-in-magento-you-are-doing-it-wrong/