Laravel - 在模型中使用hasMany计算选项

时间:2016-04-15 14:38:37

标签: php eloquent laravel-5.1

我有以下情况:

我有一些问题,这些问题有可能的答案。我想计算每个问题每个项目的回答次数。

为此,我有3张桌子:

  • 问题
  • 答案
  • Answers_questions

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

在查看每个问题之后,只显示计数的第一个答案。

如何解决?

感谢!!!

1 个答案:

答案 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'));
}