2011-12-12 36 views
1

沒有人似乎有這個問題,所以要麼我做錯了或沒有人嘗試過:CakePHP Containable不會觸發包含模型上的其他行爲的回調?

我有一個模型「信息中心」,它有很多「信息中心文章」。爲了獲取包含相關內容的數據,我將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)簽名應該沒問題,我仔細檢查。

4)我正在使用CakePHP 1.3。

感謝您的幫助。

+0

你確定了一個afterFind()不點火?你有沒有嘗試將一些調試代碼作爲afterFind()中的第一行來確保它沒有被調用,afterFind()中的某些內容不起作用? 此外,請確保您的afterFind()參數匹配Cake Cookbook中的那些參數(您不會說您正在使用哪個版本的CakePHP,1.3和2有不同的afterFind簽名) – RichardAtHome

+0

我在您的問題中添加了您請求的信息。 – Rekhyt

+0

afterFind在模型中適用於我,但不適用於由同一模型使用的行爲的afterFind。 –

回答

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-data

0

我只是寫了一篇關於如何處理這類情況的大量進入。

它適用於CakePHP 2.x和PHP 5.4+。

Containable behavior alternative function

+0

請注意,[只有鏈接的答案](http://meta.stackoverflow.com/tags/link-only-answers/info)不鼓勵,所以答案應該是搜索解決方案的終點(vs.而另一個引用的中途停留時間往往會隨着時間推移而過時)。請考慮在此添加獨立的摘要,並將鏈接保留爲參考。 – kleopatra