php Laravel口才:基于关系选择随机行

hjzp0vay  于 2023-01-12  发布在  PHP
关注(0)|答案(1)|浏览(173)

bounty将在5天后过期。回答此问题可获得+50的声誉奖励。OutForCode正在寻找来自声誉良好来源的答案

我想随机抽题但要有类别依赖性,比如考试给了10道题,总类别是5个,那么考试流程要从每个类别中随机抽2道题,有没有办法通过随机和口才的关系来选择呢?
和问题表

+-------+-------+-------+-------+
|  id   |  category_id  |.......|
+-------+-------+-------+-------+

我已经使用随机雄辩,但从每个类别的问题的概率很低

public getRandomQuestions($limit)
{
    $this->inRandomOrder()->limit($limit)->get()
}

而我在谈恋爱的时候却毫无头绪。

mkshixfv

mkshixfv1#

每个类别获取1个随机问题的查询:

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;

说明:

  • 由于您希望问题是随机的,我们需要order by rand(),注意:inRandomOrder还在幕后使用order by rand()
  • 为了能够为每个类别获得2个问题,我们需要一个变量(@position)来标记问题的顺序

laravel实施:

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());
}

相关问题