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.
category_id
the query to get 1 random question for each category:
SELECT *
FROM
(SELECT *,
@position := IF(@current_cate=category_id, @position + 1, 1) AS POSITION,
@current_cate := category_id
FROM
(SELECT q.*
FROM category c
INNER JOIN question q ON c.id = q.category_id
ORDER BY RAND()) temp
ORDER BY category_id) temp1
WHERE POSITION <= 2
ORDER BY category_id;
explanation:
order by rand()
, note: inRandomOrder
also uses order by rand()
under the hood@position
) to mark the order of questionlaravel implementation:
public getRandomQuestions($limit)
{
$questions = DB::select("SELECT *
FROM
(SELECT *,
@position := IF(@current_cate=category_id, @position + 1, 1) AS POSITION,
@current_cate := category_id
FROM
(SELECT q.*
FROM category c
INNER JOIN question q ON c.id = q.category_id
ORDER BY RAND()) temp
ORDER BY category_id) temp1
WHERE POSITION <= 2
ORDER BY category_id");
return Question::hydrate($questions->toArray());
}