Reputation: 2893
I have a backend where I can create a Poll. Within a Poll I can create a PollQuestion. And for a PollQuestion, I can create many PollAnswer's.
If I do something like this in my Controller
$poll = DB::table('poll')->orderBy('id', 'desc')->first();
$question = DB::table('poll_question')->where('poll_id', $poll->id)->first();
$answers = DB::table('poll_answer')->select('answer')->where('question_id', $question->id)->get();
print_r("<pre>");
print_r($answers);
print_r("</pre>");
I can see an output like the following
Array
(
[0] => stdClass Object
(
[answer] => Answer 1
)
[1] => stdClass Object
(
[answer] => Answer 2
)
[2] => stdClass Object
(
[answer] => Answer 3
)
[3] => stdClass Object
(
[answer] => Answer 4
)
)
So, the above Poll was given 4 possible answers to the PollQuestion.
Now I have a frontend which displays the question, and a radio button for each PollAnswer. When they select one and save, I get a PollResponse. If I do something like this
$pollResponses = DB::table('poll_response')->select('response')->where('poll_id', $poll->id)->get();
The output might be something like this
Array
(
[0] => stdClass Object
(
[response] => Answer 1
)
[1] => stdClass Object
(
[response] => Answer 4
)
[2] => stdClass Object
(
[response] => Answer 4
)
[3] => stdClass Object
(
[response] => Answer 2
)
[4] => stdClass Object
(
[response] => Answer 3
)
)
So I can see what people have selected. Now, for each possible PollAnswer, I need to count the number of PollResponse which relate to it. So for the above data, I should get something like
1 = 1
2 = 1
3 = 1
4 = 3
Is there any easy way I can do this in Laravel, or would I need to loop both the Answers and Responses to get the individual counts?
Upvotes: 2
Views: 392
Reputation: 347
Assuming that you're using models,you can do this in Laravel
$polls = Poll::with(['questions.answers'])->get();
Your Poll.php file
...
class Poll extends Model{
public function questions(){
return $this->hasMany(Question::class);
}
}
Your Question.php file
...
class Question extends Model{
public function answers(){
return $this->hasMany(Answer::class);
}
}
And then in your view file (assuming it's .blade.php)
@foreach($polls as $poll)
@foreach($poll->questions as $question)
{{ $question->title }}
<ul>
@foreach($question->answers as $answer)
<li>{{ $answer->title }} </li>
@endforeach
</ul>
@endforeach
@endforeach
Upvotes: 1
Reputation: 97
I don't know of any laravel-specific solution, but you can always push the responses to a separate array and then use the php function array_count_values($array)
(http://php.net/manual/en/function.array-count-values.php) on the new array.
$newArray = array();
for($i=0; $i < count($pollResponses); $i++){
array_push($newArray, $pollResponses[$i]->response);
};
$count = array_count_values($newArray);
It will return a two dimensional array with the answer as the key and the number of times it occurs as the value.
Upvotes: 2