我有这样的数据库结构:
表:
用户(id,email,密码,...)//默认laravel用户表
考生(id,user_id,...)
exam_quizzes(id,title,explanation)
exam_quiz_answers(id,title,exam_quiz_id,is_correct_ans)
submitted_answers(id,user_id,exam_quiz_id,exam_quiz_answer_id)
我已经设置了相应的模型和关系方法。
型号:
User, Examinee, ExamQuiz, ExamQuizAnswer, SubmittedAnswer
关系:
// User -> hasOne() -> Examinee
$user->examinee
// ExamQuiz -> hasMany() -> ExamQuizAnswer
$examQuiz->examQuizAnswers
// SubmittedAnswer -> hasMany() -> ExamQuiz
$submittedAnswer->examQuizzes
// SubmittedAnswer -> hasMany() -> ExamQuizAnswer
$submittedAnswer->examQuizAnswers
// User -> hasMany() -> SubmittedAnswer
$user->submittedAnswers
在我看来,如何为每位同时也是受检者的用户显示名称,总回答和总体正确像这样的表:
<tr>
<th>Name</th>
<th>Answered</th>
<th>Correct</th>
</tr>
@foreach()
{{-- I have no idea what to do here --}}
<tr>
<td></td>
<td></td>
<td></td>
</tr>
@endforeach
答案 0 :(得分:2)
在你的控制器中,你让用户通过它来查看。
$users = User:get();
并制作一个foreach循环来获得答案并正确答案:
<tr>
<th>Name</th>
<th>Answered</th>
<th>Correct</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{count($user->submittedAnswers()->get())}}</td>
@php
foreach($user->submittedAnswers()->get() as $answer){
foreach($answer->examQuizAnswers->get() as $quiz){
$count = $quiz->where('is_correct_answer',1)->count()
}
}
@endphp
<td>{{$count}}</td>
</tr>
@endforeach
但是当然你可以在模型中编写一个方法来检索正确的答案。而只是调用该方法。 您可以在用户模型中编写这样的方法:
public function get_correct_answers($user_id){
$user = User::whereId($user_id)->first();
foreach($user->submittedAnswers()->get() as $answer){
foreach($answer->examQuizAnswers->get() as $quiz){
$count = $quiz->where('is_correct_answer',1)->count()
}
}
return $count;
}
然后在视图中你只需要调用这个方法:
<tr>
<th>Name</th>
<th>Answered</th>
<th>Correct</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{count($user->submittedAnswers()->get())}}</td>
<td>{{$user->get_correct_answers($user->id)}}</td>
</tr>
@endforeach
答案 1 :(得分:1)
循环你的$ users并回显你想要的3个字段。大致像这样:
{{ $user->name }}
{{ $user->submittedAnswers->examQuizAnswers()->where('is_correct_answer', 1)->get()->count() }}
{{ $user->submittedAnswers->examQuizAnswers->count() }}
但请不要为了孩子而在视图文件中查询。
控制器中与预加载相关的模型:
User::with(['submitted_answers', 'submitted_answers.exam_quiz_answers'])->get()