我是php和幼虫的新手。我有以下数据库表问题和答案。每个问题可以有多个答案,更正后的答案显示在正确答案字段中。我正在尝试列出问题,答案如下
这是个问题。 A. 第一个答案 B. 第二个答案 C. 第三个答案 D. 第四个答案
我有以下代码:
public static function getMultipleChoiceQuestions($chapter)
{
$data = DB::table('newQuestions')
->join('newAnswers', 'newQuestions.questionId', '=', 'newAnswers.questionId')
->where('chapterId', '=', $chapter)->orderBy('newQuestions.questionId')
->where('questionType', '=', "1")
->get();
$questions = array('questionType' => $questionType, 'data' => $data);
return $questions;
}
问题表: 章节编号 问题标识 问题文本
答题表: 答案标识 问题标识 回答文本 正确答案
以下代码显示每个答案的问题。
<fieldset id="group_1">
<p><div><input type="checkbox" class="checkall"> Check all</div></p>
<div style="width:600px; height:300px; overflow: auto;">
@foreach($questions['data'] as $question)
<p><input name="your_name" value="{{ $question->questionId }}" id="{{ $question->questionId }}" type="checkbox" class="questionsOnPage" />
{{ $question->questionText }}</p>
@endforeach
</div>
</fieldset>
我想列出问题,然后回答,然后下一个问题。
请帮忙!
我认为你需要进一步看看Eloquent。 你应该能够做这样的事情。
下面介绍了如何建立关系。 基于此,您的答案表名称需要answers
,并且需要一个名为 question_id
的列。 不过,您可以浏览文档以了解如何设置自定义表名和列名。
应用程序/模型/问题.php
class Question extends Eloquent {
public function answers()
{
return $this->hasMany('Answer');
}
}
应用/模型/答案.php
class Answer extends Eloquent {
public function question()
{
return $this->belongsTo('Question')
}
}
现在,一旦这些关系被这样设置,我们就可以真正使用Eloquent。 您可以使用刀片在视图中轻松执行此类操作。
外部 foreach 将循环遍历每个问题。 内部 foreach 将显示属于当前问题的每个答案,然后转到下一个问题。
@foreach(Question::all() as $question)
<h3>{{ $question->title }}</h3>
<ul>
@foreach($question->answers->all() as $answer)
<li>{{$answer->text}}</li>
@endforeach
</ul>
@endforeach
您在此处看到的 title
和 text
属性只需要是数据库中的列名。 您应该更改它们以匹配您的。
使用上面的示例,您应该能够根据需要设置样式并将其放置在表单中。 现在,它将在 h3 标签中显示问题,然后在其下方显示一个无序列表,其中包含答案。