无法使用codeigniter 3在SQL中获取具有相同外键的多行

r6hnlfcb  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(105)

我使用code igniter 3创建了一个Web应用程序,从3个表中获取数据并在视图中显示它们(quiz_table,question_table和answers_table)。该应用程序是一个测验应用程序(MCQ quiz)。x1c 0d1x

一个测验包含4个问题,每个问题包含4个答案,其中只有一个正确。
我编写了一个SQL查询来检索所有3个表中的数据,例如测验表、创建者姓名、评分、问题ID、问题标题、正确答案和该问题的答案列表。我正在尝试引用答案表的问题ID并获取问题的所有4个答案。
以下是型号代码,

function getSingleQuizQuestionDataFromDB($quizId)
{        //insert query
    try {
        $this->db->select('quiz_table.quizName');
        $this->db->select('quiz_table.creatorName');
        $this->db->select('quiz_table.rating');
        $this->db->select('question_table.questionId');
        $this->db->select('question_table.questionTitle');
        $this->db->select('question_table.correctAnswer');
        $this->db->select('answer_table.answer');
        $this->db->from('quiz_table');
        $this->db->where('quiz_table.quizId',$quizId);
        $this->db->join('question_table','question_table.quizId = quiz_table.quizId','INNER');
        $this->db->join('answer_table','answer_table.questionId= question_table.questionId');
        $this->db->group_by(['quiz_table.quizId', 'question_table.questionId']);
        $result = $this->db->get();

        $singleQuizQuestionData= $result->result_array();
        return $singleQuizQuestionData;
    } catch (Exception $e) {
        // log_message('error: ',$e->getMessage());
        return;
    }
}

下面是我从这个查询中得到的结果,

{
"singleQuizQuestionData": [
  {
     "quizName": "quiz 1",
     "creatorName": "kavibebi",
     "rating": "0",
     "questionId": "76",
     "questionTitle": "q1q1",
     "correctAnswer": "q1a",
     "answer": "q1q1a1"
  },
  {
     "quizName": "quiz 1",
     "creatorName": "kavibebi",
     "rating": "0",
     "questionId": "77",
     "questionTitle": "q1q2",
     "correctAnswer": "q1a",
     "answer": "q1q2a1"
  },
  {
     "quizName": "quiz 1",
     "creatorName": "kavibebi",
     "rating": "0",
     "questionId": "78",
     "questionTitle": "q1q3",
     "correctAnswer": "q1a",
     "answer": "q1q3a1"
  },
  {
     "quizName": "quiz 1",
     "creatorName": "kavibebi",
     "rating": "0",
     "questionId": "79",
     "questionTitle": "q1q4",
     "correctAnswer": "q1a",
     "answer": "q1q4a1"
  }
  ]
  }

正如你在上面看到的,这个查询只返回每个问题的第一个答案。我怎样才能在响应中得到一个问题的所有4个答案?请帮助!

jaxagkaj

jaxagkaj1#

$singleQuizData = array();
foreach ($singleQuizQuestionData as $row) {
  // If this is the first row for a new question, create a new array for the 
  // question
    $singleQuizData[$row['questionId']] = array(
      'quizName' => $row['quizName'],
      'creatorName' => $row['creatorName'],
      'rating' => $row['rating'],
      'questionId' => $row['questionId'],
      'questionTitle' => $row['questionTitle'],
      'correctAnswer' => $row['correctAnswer'],
      'answers' => $row['answer'],
    );
  }

// The $singleQuizData array should now contain one element for each question

相关问题