CakePHP中的动态模型关系 [英] Dynamic model relations in CakePHP
问题描述
我正在尝试根据环境变量来定义特定模型的关系.
像这样:
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.
现在出现的问题是:如果Page
模型与例如Paragraph
模型并从我正在尝试的BookController中获取:
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会告诉我Paragraph
与Page
模型无关.
... 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(
// ...
)
);
}
这是为什么?我需要手动建立那些关系吗?我的时间(__construct()
)是否不正确,应该在其他地方进行吗?
Why is this? Do I need to manually establish those relations? Is my timing (__construct()
) incorrect and should this be done elsewhere?
亲切的问候, 巴特
推荐答案
是的,您的时间安排不正确.您应该在调用父构造函数之前 应用以下配置选项:
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);
或使用Model::bindModel()
代替,这将创建必要的链接:
or use Model::bindModel()
instead which will create the necessary links:
$this->bindModel(
array('hasMany' => array(
'Page' => array(
// ...
'conditions' => array( /* ... */ )
)
)),
false
);
另请参见 http://book.cakephp.org/...html#creating-and-destroying-associations-on-fly
这篇关于CakePHP中的动态模型关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!