Cakephp计算平均问题

时间:2011-05-20 10:27:52

标签: 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"));

我用它来输出数据:

<?php foreach($grades as $grade): ?>
    <tr>
        <td><?php echo $grade['Grade']['AVG(grade)']; ?></td>
    </tr>
<?php endforeach;?>

但它给了我一个“未找到警告指数等级”。我怀疑它与['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
                )

        )

)

3 个答案:

答案 0 :(得分:6)

首先,执行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']

答案 1 :(得分:0)

执行SELECT AVG(grade) AS avg_grade这将是可用的 $grades['Grade']['avg_grade']

答案 2 :(得分:0)

在cakephp 3.5

下面查询我的工作

//用户是我的表
//默认情况下,用户评分在表格中为0,这就是为什么设置where子句&gt; 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