06.15 php
AD7six
Note
AD7six did not leave a note
  1. <?php
  2. class Rating extends AppModel {
  3.     var $belongsTo = array(
  4.             'User',
  5.             'Service' => array(
  6.                 'counterCache' => true,
  7.                 'counterScope' => array('Rating.status' => '> 0'),
  8.                 'avgCache' => true,
  9.                 'avgScope' => array('Rating.status' => '> 0'),
  10.             ),
  11.             'Provider' => array(
  12.                 'counterCache' => true,
  13.                 'counterScope' => array('Rating.status' => '> 0'),
  14.                 'avgCache' => true,
  15.                 'avgScope' => array('Rating.status' => '> 0'),
  16.             )
  17.     );
  18.     var $validate = array(
  19.         'comment' => array(
  20.             'rule' => array('minLength', 5)
  21.         )
  22.     );
  23.     function updateCounterCache($keys = array()) {
  24.         parent::updateCounterCache($keys);
  25.         if (empty($keys)) {
  26.             $keys = $this->data[$this->alias];
  27.         }
  28.         foreach ($this->belongsTo as $parent => $assoc) {
  29.             if (!empty($assoc['avgCache'])) {
  30.                 if ($assoc['avgCache'] === true) {
  31.                     $assoc['avgCache'] = Inflector::underscore($this->alias) . '_avg';
  32.                 }
  33.                 if ($this->{$parent}->hasField($assoc['avgCache'])) {
  34.                     $conditions = array($this->escapeField($assoc['foreignKey']) => $keys[$assoc['foreignKey']]);
  35.                     if (isset($assoc['avgScope'])) {
  36.                         $conditions = array_merge($conditions, (array)$assoc['avgScope']);
  37.                     }
  38.                     $fields = 'AVG(rate) AS rate';
  39.                     $recursive = -1;
  40.                     list($edge) = array_values($this->find('first', compact('conditions', 'fields', 'recursive')));
  41.                     $average = ife(empty ($edge['rate']), 0, $edge['rate']);
  42.                     $this->{$parent}->updateAll(
  43.                         array($assoc['avgCache'] => $average),
  44.                         array($this->{$parent}->escapeField() => $keys[$assoc['foreignKey']])
  45.                     );
  46.                 }
  47.             }
  48.         }
  49.     }
  50. }
  51. ?>
Parsed in 0.113 seconds, using GeSHi 1.0.7.14

Modify this Paste