似乎没有人对此有问题,所以要么是我做错了,要么是没有人尝试过:
我有一个模型"Infocenter",它有许多"InfocenterArticle"。为了获取包括相关内容在内的数据,我将Containable行为附加到两者上。
这工作得很好,直到现在,我附加了一个"HasImageAttachment"的行为实现自己。问题是,在包含的模型中,我的行为的回调不会被调用。
我的模型:
class Infocenter extends AppModel {
...
$actsAs = array('HasImageAttachment', 'Containable');
$hasMany = array('InfocenterArticle');
...
}
class InfocenterArticle extends AppModel {
...
$actsAs = array('Containable');
$belongsTo = array('Infocenter');
...
}
在我的控制器中,我调用:
$conditions = array('InfocenterArticle.id' => $id);
if ($this->notLoggedIn()) $conditions['InfocenterArticle.freigabe'] = 1;
$article = $this->InfocenterArticle->find('first', array(
'contain' => array(
'Infocenter',
'Infocenter.InfocenterArticle' => array(
'fields' => array('id', 'title', 'freigabe'),
'order' => array(
'InfocenterArticle.order_index' => 'desc',
'InfocenterArticle.created' => 'desc',
'InfocenterArticle.title' => 'asc'
),
'conditions' => array(
'InfocenterArticle.infocenter_id' => 'Infocenter.id'
),
),
),
'conditions' => $conditions,
));
我可以看到,我的HasImageAttachmentBehavior::setup()方法被调用,但HasImageAttachmentBehavior::afterFind()(以及beforeFind())不是。虽然调用了Infocenter::afterFind(),但它使我能够进行一些肮脏的黑客攻击,现在已经足够好了,但我讨厌它。
我做错了什么?
编辑:回复RichardAtHome评论的附加信息
1)我的行为适用于没有Containable附加的模型。
2)我确保afterFind()不会通过放置一个简单的die()来调用;在第一行。脚本不会死()。
3)签名应该没问题,我仔细检查过了。我使用的是CakePHP 1.3.
谢谢你的帮助。
目前我不相信CakePHP核心支持跨包含模型的行为。
这可能是由于可能的递归,如果你有奇怪的包含数组的行为可能会被错误地调用。
有一篇关于CakePHP灯塔项目的长文,是关于在关联模型上调用行为的,并提供了一些解决方法的建议。
http://cakephp.lighthouseapp.com/projects/42648/tickets/95-afterfind-and-beforefind-callbacks-not-working-on-associated-models-was-translate-behavior-should-translate-associated-model-data我刚刚写了一篇关于如何处理这种情况的长篇文章。
这是CakePHP 2。
可包含行为替代函数
显然这是一个故意的设计点(?? ?!?)所以如果你想要关联的模型完全像模型一样,你就必须升级到3.0。叹息。
这里有一个广泛的讨论:https://github.com/cakephp/cakephp/issues/1730最直接的食谱修复:https://schneimi.wordpress.com/2009/09/06/behavior-afterfind-on-model-associations/