vendredi 15 avril 2016

Laravel - Count options with hasMany in a Model

I have the following situation:

I have some questions and this questions has possible answers. I would like to count how many times were answered each item for each question.

For this I have 3 tables:

  • Questions
  • Answers
  • Answers_questions

In the Answers_questions I have this relationship:

public function question(){
    return $this->belongsTo('App\Question', question_id, 'id');
}

and

public function answers(){
    return $this->hasMany('App\Answers', 'question_id', 'question_id');
}

To retrieve this informations, in the Controller I use this:

$answers_questions = new Answers_questions;
$questions = $answers_questions->groupBy('question_id')->get();

In the view:

@foreach($questions as $question)

{{ $question->question }}

  @foreach($question->answer as $answer)
    Answer: {{ $answer->answer}} - **Count: ???**

  @endforeach
@endforeach

So, How can I count this to show in my view? I tryied this:

return $this->hasMany('App\Answers', 'question_id', 'question_id')->selectRaw('*, count(answer) as count');

And after in the view for each question, just showed the first answer with the count.

How to solve?

Thanks!!!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire