我正在尝试在控制器中编写查询以向学生显示测验结果。我有这些桌子
CREATE TABLE IF NOT EXISTS `quizz_question` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`topic` varchar(1000) COLLATE utf8_unicode_ci NOT NULL,
`question_code` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`answer1` varchar(100) COLLATE utf8_unicode_ci NULL,
`answer2` varchar(100) COLLATE utf8_unicode_ci NULL,
`answer3` varchar(100) COLLATE utf8_unicode_ci NULL,
`answer4` varchar(100) COLLATE utf8_unicode_ci NULL,
`topic` varchar(1000) COLLATE utf8_unicode_ci NOT NULL,
`correct_answer` varchar(100) COLLATE utf8_unicode_ci NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10 ;
CREATE TABLE IF NOT EXISTS `quizz_attempt` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`student_code` varchar(1000) COLLATE utf8_unicode_ci NOT NULL,
`answer` varchar(100) COLLATE utf8_unicode_ci NULL,
`question_code` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10 ;
这两个表成为了这两个模型类:QuizzQuestion和QuizAttempt。
在quizz_attempt中,如果学生选择一个答案(answer),它将在quizz_attempt中获取答案和问题代码,并与quizz_question进行比较。
quizz_attempt.answer = 1,它将选择答案1中的内容作为正确答案
quizz_attempt.answer = 2,它将选择answer2中的内容作为正确答案
quizz_attempt.answer = 3,它将选择答案3中的内容作为正确答案
quizz_attempt.answer = 4,它将选择答案4中的内容作为正确答案
public function gameQualifiers(Request $request)
{
$revenuedetails = DB::table('quizz_attempt as g')
->select(
'g.student_code',
'g.answer'
)
->orderByRaw('g.created_at DESC');
}
我知道我需要将两个表连接起来以获得结果。我在控制器中启动了代码,但不知道如何完成。我想写一个查询来显示选择正确答案的学生的名单
答案 0 :(得分:0)
测验尝试应将quizz_question_id
作为外键。这样可以更容易地将两者连接起来。
您可以设置两个模型来匹配数据库表:QuizzQuestion和QuizzAttempt。您可以这样设置外键:
QuizzAttempt.php
public function quizzQuestion()
{
return $this->belongsTo('App\QuizzQuestion');
}
和QuizzQuestion.php
public function quizzAttempts()
{
return $this->hasMany('App\QuizzQuestion');
}
所以现在,您想获得所有答案正确的尝试-您正在查看QuizzQuestion的实例,例如
$question = QuizzQuestion::find(1); // first question
$correctResults = QuizzAttempts::where('quizz_question_id', $question->id)
->where('answer', $question->correct_answer)
->pluck('student_code');`
现在,您已经掌握了所有正确答案的学生的学生密码。
***更新
如果无法更改表的结构,则可以运行以下查询:
// 1) find the question you want the answers for
$question = QuizzQuestion::find(1);
// 2) retrieve the correct results
$correctResults = QuizzAttempts::where('question_code', $question->question_code)
->where('answer', $question->correct_answer)
->pluck('student_code');`