对于find('count',array('group'=>'user_id'));
Model.php中这样描述:
1 /** 2 * Handles the before/after filter logic for find('count') operations. Only called by Model::find(). 3 * 4 * @param string $state Either "before" or "after" 5 * @param array $query 6 * @param array $results 7 * @return integer The number of records found, or false 8 * @see Model::find() 9 */ 10 protected function _findCount($state, $query, $results = array()) { 11 if ($state === 'before') { 12 if (!empty($query['type']) && isset($this->findMethods[$query['type']]) && $query['type'] !== 'count') { 13 $query['operation'] = 'count'; 14 $query = $this->{'_find' . ucfirst($query['type'])}('before', $query); 15 } 16 17 $db = $this->getDataSource(); 18 $query['order'] = false; 19 if (!method_exists($db, 'calculate')) { 20 return $query; 21 } 22 23 if (!empty($query['fields']) && is_array($query['fields'])) { 24 if (!preg_match('/^count/i', current($query['fields']))) { 25 unset($query['fields']); 26 } 27 } 28 29 if (empty($query['fields'])) { 30 $query['fields'] = $db->calculate($this, 'count'); 31 } elseif (method_exists($db, 'expression') && is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) { 32 $query['fields'] = $db->calculate($this, 'count', array( 33 $db->expression($query['fields']), 'count' 34 )); 35 } 36 37 return $query; 38 } 39 40 foreach (array(0, $this->alias) as $key) { 41 if (isset($results[0][$key]['count'])) { 42 if ($query['group']) { 43 return count($results); 44 } 45 46 return intval($results[0][$key]['count']); 47 } 48 } 49 50 return false; 51 }
在cakephp测试用例中,有这样的描述:
1 $expected = count($Article->find('all', array( 2 'fields' => array('Article.user_id'), 3 'conditions' => array('Article.user_id' => 1), 4 'group' => 'Article.user_id') 5 )); 6 $result = $Article->find('count', array( 7 'conditions' => array('Article.user_id' => 1), 8 'group' => array('Article.user_id'), 9 ));
$expected 和 $result 的结果是一样的。那么使用count,group统计也是可行的。
使用find('count',array('fields'=>'distinct user_id'));效果也是一样的。