Dynamic model relations in CakePHP

徘徊边缘 提交于 2020-01-06 08:37:47

问题


I'm trying to define the relations for a specific Model depending on environment variables.
Like this:

class Book extends AppModel {
    public function __construct($id = false, $table = null, $ds = null) {
        parent::__construct($id, $table, $ds);

        if (Configure::read('prefix') == 'admin') {
            $this->hasMany['Page'] = array(
                // ...
                'conditions' => array( /* all pages */ )
            );
        } else {
            $this->hasMany['Page'] = array(
                // ...
                'conditions' => array( /* only public pages */ )
            );
        }
    }
}

You could argue that I should apply these conditions in the query. But because I'm working with deeply nested relations I wanted to keep conditions centralised.

Now the problem that occurs is: if the Page model has relations to e.g. the Paragraph model and from the BookController I'm trying:

$this->Book->find('first', array(
    'conditions' => array('Book.id'=>1),
    'contain' => array('Page' => array('Paragraph'))
));

... CakePHP will tell me that Paragraph is not related to the Page model.

If I create the relation by defining a model attribute all goes well:

class Book extends AppModel {
    public $hasMany = array(
        'Page' => array(
            // ...
        )
    );
}

Why is this? Do I need to manually establish those relations? Is my timing (__construct()) incorrect and should this be done elsewhere?

Kind regards, Bart


回答1:


Yes, your timing is incorrect. You should either apply these configuration options before invoking the parent constructor:

if (Configure::read('prefix') == 'admin') {
    // ...
}

parent::__construct($id, $table, $ds);

or use Model::bindModel() instead which will create the necessary links:

$this->bindModel(
    array('hasMany' => array(
        'Page' => array(
            // ...
            'conditions' => array( /* ... */ )
        )
    )),
    false
);

See also http://book.cakephp.org/...html#creating-and-destroying-associations-on-the-fly



来源:https://stackoverflow.com/questions/24244011/dynamic-model-relations-in-cakephp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!