0

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.

1 Answer 1

2

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)
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.