CakePHP:限制控制器中的关联

时间:2014-11-09 22:05:14

标签: cakephp cakephp-2.3 cakephp-appmodel

作为一个例子让我们想象一下我们有一个简单的电视节目数据库。显示和剧集作为模型。 剧集属于一个节目,一个节目有很多剧集。

在剧集/索引视图中,我们只是回显所有剧集,同样适用于节目/索引视图。但我也希望回应一下,让每个节目的前5集(只是标题)。我可以通过设置hasMany关联的limit属性来限制剧集。

在show / episode / x(id)视图中,我想回应所有剧集。因此,我不能简单地为hasMany关联使用limit属性,因为它依赖于视图。

我应该选择实施哪种解决方案?我只能通过使用一些“肮脏的解决方法/黑客”来存档,但我觉得这是一个常见的问题,可能会有一些实际的解决方案。

1 个答案:

答案 0 :(得分:2)

我相信你所寻找的是可以控制的行为。

阅读文档:

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

然后删除您的关联限制。下面介绍了如何在示例中使用可包含行为。

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)
        );
    }
}