GroupBy and Count-Laravel

时间:2018-07-16 07:35:55

标签: php laravel

在我的应用程序中,我发送调查并分组并计算相似和不相似的回复。这就是我的小组和计数现在工作的方式

注意:以本例为例,该调查好像有2位客户回答了。

客户端1和客户端2都为问题1选择了Good

回复

question                                     Ans

How would you describe my services?          Good (2) 
How would you describe my services?          Good (2) 


Gender                                       Male(1)
Gender                                       Female(1)

如何取出冗余。当答案随着计数而重复时,问题也会重复。

回复

question                                Name         Ans

How would you describe my services?                Good (2) 


Gender                                             Male(1), Female(1)

模型

public function count_answers() 
  {        
    return $this->hasMany(Answer::class)->select('answer', DB::raw('count(*) as counter'))->groupBy('answer');
  }

查看

@forelse ($data->questions as $item)
@foreach ($item->answers as $answer)
<tr>     
 <td width="30%">{{ $item->title }}</td>
 <td>
@foreach ($item->count_answers as $answer)
 <div>{{$answer->answer}} ({{$answer->counter}})</div>
@endforeach    
</td> 
</tr>
@endforeach

控制器

 public function view_survey_response(Survey $data) 
  {
    $data = Survey::where('id', $data->id)->where('user_id', Auth::user()->id)->first();

    return view('answer.response', compact('data'));
  };

0 个答案:

没有答案