We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Average count in column which has same id

I am trying to display average of column which has same user_id:

    $average = Rating::average(
        [
            'column'     => 'rating',
            'group' => 'user_id',
        ]
    );
    $this->view-> averages = $average;

Volt:

      {% for average in averages %}
    <tr>
        <td>{{ averages.rating }}</td>
    </tr>
       {% endfor %}

But it returns all the values, not average of values with same user_id.



85.5k

group by user_id ?

edited Jan '18

Tested your exact code and it is working fine for me?

Array
(
    [0] => Array
        (
            [product_id] => 1
            [average] => 4.5000
        )

    [1] => Array
        (
            [product_id] => 2
            [average] => 3.8571
        )

)

UPDATE! Just noticed a typo in your code:

This <td>{{ averages.rating }}</td> should be <td>{{ average.rating }}</td> your item is average, not averageS.



85.5k

oh lord, my comment is totaly useless, you already grouped by user id, was too early in the morning so i didnt see it :D

edited Jan '18

I always get this:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "user_id" Undefined property: Phalcon\Mvc\Model\Row::$rating

It looks like I can't reach my main model of table. Without average function table are displayed correctly. Maybe this function is problem?



85.5k

maybe model meta data cache problem ?



43.9k

Hi,

try with:

<td>{{ average.average }}</td>



43.9k

<td>{{ average.user_id }}</td><td>{{ average.average }}</td>

should work to !