【问题标题】:Looping and building a dynamic data Table循环构建动态数据表
【发布时间】:2017-03-25 23:51:00
【问题描述】:

我正在构建一个显示调查结果信息的应用程序。在每个调查中,我都有问题,每个问题都有他的答案。

但是我在构建表格时遇到了一些问题,标题表和正文是动态构建的,标题是问题,正文是答案。

我的代码表示例:

<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);
    }

}

截图

【问题讨论】:

    标签: php laravel laravel-5 eloquent laravel-5.3


    【解决方案1】:

    据我了解,通过question_id下单。还注意到您要查询 3 次,我建议您查询一次并将其存储在变量中并使用它。

    @php
        $results = $survey->answers->groupBy('email')->orderBy('question_id');
    @endphp
    ...
    @foreach($results->first() as $answer)
    ...
    

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 2020-03-21
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 2021-03-31
      • 1970-01-01
      相关资源
      最近更新 更多