DaD*_*aDu 1 php sql cakephp average
我有这个问题:
$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"));
Run Code Online (Sandbox Code Playgroud)
我用它来输出数据:
<?php foreach($grades as $grade): ?>
<tr>
<td><?php echo $grade['Grade']['AVG(grade)']; ?></td>
</tr>
<?php endforeach;?>
Run Code Online (Sandbox Code Playgroud)
但它给了我一个"未找到警告指数等级".我怀疑这与它有关,['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
)
)
)
Run Code Online (Sandbox Code Playgroud)
首先,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'
)
);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,当你做foreach( $grades as $grade )
平均值将在$grade[0]['average']
.
归档时间: |
|
查看次数: |
3572 次 |
最近记录: |