I have the following database scheme:
table \'products\'
id
category_id
and of course a category table, just with an id.
The data look
You first have to count the total number of products, then generate a random offset to select a random product.
This should get you started:
$count = $this->createQueryBuilder('u')
->select('COUNT(u)')
->getQuery()
->getSingleScalarResult();
And then you can generate a random number between your 1 and the total number of rows.
return $this->createQueryBuilder('u')
->where('u.category = :category')
->setFirstResult(rand(0, $count - 1))
->setMaxResults(1)
->setParameter('category', $category->getId())
->getQuery()
->getSingleResult()
;
Which translates to:
SELECT * FROM products WHERE category_id = ? LIMIT 1, {random offset}