我有班级,每个班级都有学生。我想得到一个表,其中包含每个班级的学生人数。在这种情况下如何找到:
$nums = $this->Student->find('count', array('group' => 'Student.Class_id'));
这个结果是不正确的
有几种方法可以归档它:
使用带有 find-all 的虚拟字段
$this->Student->virtualFields = array('count' => 'COUNT(Student.' . $this->Student->primaryKey .')');
$this->Student->find("all", array('fields' => 'count', 'group' => 'Student.Class_id'));
构建自定义查询
$this->Student->query("SELECT COUNT(Student.{$this->Student->primaryKey}) as 'count' FROM students Student GROUP BY Student.Class_id");