【问题标题】:Cakephp best way to store count of children's childrenCakephp存储孩子数量的最佳方法
【发布时间】:2013-07-17 22:09:41
【问题描述】:

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

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

我最近发现了 counterCache,但这只有在学生直接属于学校时才有效。我正在考虑通过在 foreach 循环中添加所有课程学生来进行手动计数。有没有更简洁的方法?

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

【问题讨论】:

  • 就我个人而言,我只是使用循环并将总数相加。

标签: php cakephp


【解决方案1】:

根据你的问题,试试下面的代码:

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;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    相关资源
    最近更新 更多