简体   繁体   中英

CakePHP - listing entries grouped by program_id

I have the following relations between my models

Program hasMany Classroom
Classroom belongsTo Program

What I am trying to achieve is to display all the classrooms, grouped by program, for example:

Program 1

-Classroom 1

-Classroom 2

-Classroom 3

Program 2

-Classroom 1

-Classroom 2... etc

My index action in ClassroomsController:

    function index() {

    $this->Access->grantAdmin();

    $this->Classroom->recursive = 1;
    $this->set('classrooms', $this->paginate());
}

I tried to use this:

    var $paginate = array(
    'group' => 'program_id'
);

But it didn't work as I expected. Any ideas? Thanks

Try adding:

var $actsAs = array('Containable');

to the Program model. Then in the controller:

$programs = $this->Classroom->Program->find('all', array(
    'contain' => array(
        'Classroom',
    ),
));
$this->set(compact('programs'));

This should return your data in the hierarchy you're looking for. See the Containable behaviour documentation for more details. Note that you don't need the $this->Classroom->recursive statement if you use Containable.

Your own code example shows that you're using pagination. It should be fairly easy to put containable and pagination together by looking around the docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM