I have this query:
$this->set('grades', $this->Grade->Query("
SELECT AVG(grade),
sections.section_name
FROM grades,
sections
WHERE sections.id = grades.section_id
AND grades.user_id =".$id."
GROUP BY grades.section_id"));
And I use this to output the data:
<?php foreach($grades as $grade): ?>
<tr>
<td><?php echo $grade['Grade']['AVG(grade)']; ?></td>
</tr>
<?php endforeach;?>
But it gives me a "warning index Gra开发者_开发百科de not found". I suspect it got to do with the ['AVG(grade)']
because when I remove the AVG(grade) it outputs normal (without avg values obviously)
Is there anyone who can help?
EDIT
debug($grades) outputs:
Array
(
[0] => Array
(
[0] => Array
(
[avg_grade] => 4.75000
)
[sections] => Array
(
[section_name] => Nederlands
)
)
[1] => Array
(
[0] => Array
(
[avg_grade] => 6.50000
)
[sections] => Array
(
[section_name] => Engels
)
)
)
First, do debug( $grades )
to see where the average is stored in the array structure. You can also name it something else in the query, for example SELECT AVG( grade ) AS average
.
As a side note, you don't need to use a raw query (perhaps a matter of preference, but I tend to avoid them if at all possible). You can do
$this->Grade->find(
'all',
array(
'conditions' => array(
'Grade.user_id' => $id
),
'recursive' => 1,
'fields' => array(
'AVG( Grade.grade ) AS average',
// +whatever else you need
)
'group' => 'Grade.section_id'
)
);
In this case when you do foreach( $grades as $grade )
the averages will be in $grade[0]['average']
.
Do a SELECT AVG(grade) AS avg_grade
this will be available as
$grades['Grade']['avg_grade']
.
Below Query work for me in cakephp 3.5
// users is my table
// By default user rating will be 0 in tables that`s why set where clause > 0
$query = $this->Users->find();
$ratingAverage = $query->select(['averageRating' => $query->func()->avg('user_rating')])
->where(['user_rating' => $userId,'provider_rating >' => 0])->group('user_rating')->first();
Refer here
精彩评论