[英]Looping and building a dynamic data Table
我正在构建一个显示调查结果信息的应用程序。 在每个调查中,我都有问题,每个问题都有答案。
但是我在构建表,标题表和主体方面存在一些问题,它们是动态生成的,其中标题是问题,主体是答案。
我的代码表示例:
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
@foreach($survey->answers->groupBy('email')->first() as $answer)
<th>{{$answer->question->internal_name}}</th>
@endforeach
</tr>
</thead>
<tbody>
@foreach($survey->answers->groupBy('email') as $answer)
<tr>
@foreach($answer as $a)
<td>{{$a->answer}}</td>
@endforeach
</tr>
@endforeach
</tbody>
<tfoot>
@foreach($survey->answers->groupBy('email')->first() as $answer)
<th>{{$answer->question->internal_name}}</th>
@endforeach
</tfoot>
</table>
我唯一遇到的问题是标题标签问题和上面的答案之间的同步性,如果问题是按不同顺序排序的,例如答案不在正确的位置,则有时是答案。
不能弄清楚我做错了什么,在我离开桌子的上方,也许有人可以知道我做错了什么。
Tables:
surveys:
- id;
- name;
questions:
- id;
- survey_id;
- label;
- internal_name;
answers:
- id;
- survey_id;
- question_id;
- answer
- email;
问题模型:
class Question extends Model
{
public function survey()
{
return $this->belongsTo(Survey::class);
}
public function answers() {
return $this->hasMany(Answer::class);
}
public function oneAnswer(){
return $this->hasOne(Answer::class);
}
}
答案模型:
class Answer extends Model
{
public function survey() {
return $this->belongsTo(Survey::class);
}
public function question() {
return $this->belongsTo(Question::class);
}
}
根据我的理解,请通过question_id
进行订购。 还应注意您要查询三次,建议一次查询一次并将其存储在变量中并使用它。
@php
$results = $survey->answers->groupBy('email')->orderBy('question_id');
@endphp
...
@foreach($results->first() as $answer)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.