1

似乎没有人对此有任何问题,所以要么我做错了,要么没有人尝试过:

我有一个模型“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)我确保不会通过放置一个简单的 die() 来调用 afterFind(); 在第一行。脚本不会死()。

3)签名应该没问题,我仔细检查了。

4) 我使用的是 CakePHP 1.3。

谢谢你的帮助。

4

3 回答 3

0

目前我不相信 CakePHP 核心支持跨包含模型的行为。

这可能是由于可能的递归,如果您有奇怪的包含数组,则可能会错误地调用行为。

CakePHP Lighthouse 项目上有一篇关于通过关联模型调用行为的长文,并提供了一些解决方法的建议。

http://cakephp.lighthouseapp.com/projects/42648/tickets/95-afterfind-and-beforefind-callbacks-not-working-on-associated-models-was-translate-behavior-should-translate-associated-model-数据

于 2012-01-24T11:20:18.310 回答
0

我刚刚写了一篇关于如何处理这种情况的详细条目。

它适用于 CakePHP 2.x 和 PHP 5.4+。

可包含的行为替代功能

于 2013-08-20T08:36:13.000 回答
0

显然这是一个刻意的设计点(??!?)。因此,如果您希望关联模型的行为与模型完全一样,则必须一直升级到 3.0。叹。

这是一个广泛的讨论:https ://github.com/cakephp/cakephp/issues/1730 和最直接的食谱修复:https ://schneimi.wordpress.com/2009/09/06/behavior-afterfind-on-模型协会/

于 2017-05-26T18:43:37.647 回答