I want to pick questions randomly but category dependent. For example, if the test is given with 10 questions and the total category is 5, the test flow should take 2 questions randomly from each category. Is there a way to select it through random and eloquent relations?
and the question table
+-------+-------+-------+-------+
| id | category_id |.......|
+-------+-------+-------+-------+
already I am using random eloquent but the probability of getting questions from each category is low
public getRandomQuestions($limit)
{
$this->inRandomOrder()->limit($limit)->get()
}
and I’m clueless when it’s coming to relations.
3
Answers
the query to get 1 random question for each category:
explanation:
order by rand()
, note:inRandomOrder
also usesorder by rand()
under the hood@position
) to mark the order of questionlaravel implementation:
You can also use the
inRandomOrder
andgroupBy
method together to select random questions from each category.This will give you 2 random questions from each category.
You can also use subquery to select questions with certain number of random questions per category
If you’re using
PHP >= 7.2
the useshuffle()
or else