【问题标题】:Laravel | Select quiz questions in random order and have the answers shown for each question拉拉维尔 |以随机顺序选择测验问题并显示每个问题的答案
【发布时间】:2018-11-28 20:49:15
【问题描述】:

我正在使用 foreach 显示所有问题,还有一个用于答案。

他们都有一个共同的 question_id。

但是如何使用两个 foreach 循环让我的应用程序知道答案属于哪里?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您能告诉我们更多细节吗? 从你提供的一些信息中我只能猜测......

    #1:创建Answer 模型

    #2:在您的Question 模型中添加与Answer 模型的关系:

    public function answers()
    {
        return $this->hasMany(Answer::class);
    }
    

    #3:随机抽取所有问题的答案:

    $questions = Questions::get();
    
    foreach ($questions as $question) {
        // getting the answer of a specific question ordered by RAND
        $answers = $question->answers()->orderByRaw("RAND()")->get();
    
        foreach ($answers as $answer) {
            // here your answer
        }
    }
    

    有关 Laravel 关系的更多信息: https://laravel.com/docs/5.7/eloquent-relationships

    【讨论】:

      【解决方案2】:

      如果您以随机顺序显示问题,则创建一个数组 $random 它将在显示问题后存储 question_id。 现在,为了显示答案,遍历 $random 数组并显示 question_id 等于 $random[$i]

      的答案
      foreach ($random as $ques_id)
          display the answer whose question_id is $ques_id
      

      【讨论】:

        猜你喜欢
        • 2015-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-07
        • 1970-01-01
        • 2017-04-04
        • 1970-01-01
        • 2018-11-01
        相关资源
        最近更新 更多