lundi 21 mars 2016

Getting count of occurences

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?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire