我有以下情况:
我有一些问题,这些问题有可能的答案。我想计算每个问题每个项目的回答次数。
为此,我有3张桌子:
在 Answers_questions 中我有这种关系:
public function question(){
return $this->belongsTo('App\Question', question_id, 'id');
}
和
public function answers(){
return $this->hasMany('App\Answers', 'question_id', 'question_id');
}
要检索此信息,请在Controller中使用:
$answers_questions = new Answers_questions;
$questions = $answers_questions->groupBy('question_id')->get();
在视图中:
@foreach($questions as $question)
{{ $question->question }}
@foreach($question->answer as $answer)
Answer: {{ $answer->answer}} - **Count: ???**
@endforeach
@endforeach
那么,我怎么能算这个在我看来呢?我试过这个:
return $this->hasMany('App\Answers', 'question_id', 'question_id')->selectRaw('*, count(answer) as count');
在查看每个问题之后,只显示计数的第一个答案。
如何解决?
感谢!!!
答案 0 :(得分:0)
我想你可以尝试这样做:
public function countAnswers(){
return count($this->hasMany('App\Answers', 'question_id', 'question_id'));
}
在重定向上查看:
public function redirectToView(){
$answers = countAnswers();
return view('your.view.file' , compact('answers'));
}