Cakephp最好的方式来存储孩子的孩子数

时间:2013-07-17 22:09:42

标签: php cakephp

好的,如果学生属于课程而课程又属于学校:

存储/获取学校所有学生人数的最佳方法是什么?

我最近发现了counterCache但这只有在学生直接上学的情况下才有效。我想通过在foreach循环中将所有课程学生相加来进行手动计数。有更简洁的方式吗?

我最好将student_count字段存储在学校表中,因为这就是我存储学校所有其他计数(课程,模块,讲师)的方式,但这可能是我挑剔的强迫症。

1 个答案:

答案 0 :(得分:0)

根据您的问题,请尝试以下代码:

function test(){
    $this->loadModel('Student');        
    $joins = array(
            array(
                'table' => 'courses',
                'alias'  => 'Course',
                'type'  => 'LEFT',
                'conditions' => array('Course.id = Student.course_id')
            ),
            array(
                'table' => 'schools',
                'alias'  => 'School',
                'type'  => 'LEFT',
                'conditions' => array('School.id = Course.school_id')
            ),
        );

        $school_wise_student_count = $this->Student->find('all', array('fields'=>array('count(Student.id) as total_student','School.name as school_name'), 'joins'=>$joins, 'group'=>array('Course.school_id')));
        pr($school_wise_student_count);
        die;

}
相关问题