2016-04-15 35 views
0

我有以下情況:Laravel - 用模型中的hasMany計數選項

我有一些問題,此問題有可能的答案。我想指出每個問題每次回答多少次。

爲此,我有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'); 
} 

要獲得這個信息,在控制器我用這個:

$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

我想你可以嘗試,例如做:

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')); 
} 
+0

我想這一點,但仍然只算第一個答案。 –

+0

你可以嘗試執行count方法: $ questions = $ answers_questions-> groupBy('question_id') - > get() - > count(); –

+0

謝謝維尼修斯。我會試試看,然後回來告訴它是否有效。 –