我有这个查询:
$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"));
我用它来输出数据:
<?php foreach($grades as $grade): ?>
<tr>
<td><?php echo $grade['Grade']['AVG(grade)']; ?></td>
</tr>
<?php endforeach;?>
但它给了我一个"找不到警告指数等级"。我怀疑这与['AVG(grade)']
有关,因为当我删除 AVG(grade) 时,它输出正常(显然没有 avg 值)
有人可以帮忙吗?
编辑
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
)
)
)
首先,debug( $grades )
查看平均值在数组结构中的存储位置。您还可以在查询中将其命名为其他名称,例如 SELECT AVG( grade ) AS average
。
作为旁注,您不需要使用原始查询(也许是偏好问题,但如果可能的话,我倾向于避免使用它们)。你可以做
$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'
)
);
在这种情况下,当您执行foreach( $grades as $grade )
平均值将以 $grade[0]['average']
为单位。
做一个SELECT AVG(grade) AS avg_grade
这将可用为
$grades['Grade']['avg_grade']
.
下面查询在 cakephp 3.5 中为我工作
用户是我的表
默认情况下,表中的用户评分将为 0,这就是为什么将 where 子句设置为 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();
参考这里