Aurus
Aurus

Reputation: 705

CakePHP: Limit associations in the controller

As an example lets imagine we have a simple tv show database. Show and Episode as Model. An Episode belongsTo one Show and one Show hasMany Episodes.

In the episodes/index view we are just echoing all episodes, the same goes for the shows/index view. But I also want to echo lets say the first 5 episodes of each show (just the title). I could simply limit the episodes by setting the limit attribute for the hasMany association.

In shows/episode/x(id) view I want to echo all episodes. And therefore I can't simply use the limit attribute for the hasMany association since it is view dependent.

What solution should I choose to implement that? I could only archive that by using some "dirty workarounds/hacks" but I feel like this is an usual problem and there might be some actual solution.

Upvotes: 0

Views: 459

Answers (1)

gmponos
gmponos

Reputation: 2277

I believe what you are looking for is the containable behaviour.

Read the doc:

http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

Then remove any limit to your associations. Below there is a way of how you can use containable behavior in your example.

class Shows extends AppModel {
    public $actsAs = array('Containable');
}

class ShowsController extends AppController {

    //Bring all the shows and 5 episodes
    public function index(){
        $this->Show->find('all', array('contain' => array(
            'Episode' => array('limit' => 5)
        )));
    }

    public function view($id){
        //Bring the show
        $this->Show->findById($id);
        //Then bring the episodes of the show
        $this->Show->Episode->findByShowId($id);

        //Or you can use
        $this->Show->find('all', array(
            'contain' => array('Episode')),
            'conditions' => array('id' => $id)
        );
    }
}

Upvotes: 2

Related Questions