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.



69.0k

group by user_id ?

edited 8d ago

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.



69.0k

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 7d ago

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?



69.0k

maybe model meta data cache problem ?



32.2k

Hi,

try with:

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



32.2k

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

should work to !