2014-06-16 81 views
0

我想根據環境變量定義特定模型的關係。
像這樣:CakePHP中的動態模型關係

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 */) 
      ); 
     } 
    } 
} 

你可以說,我應該在查詢中應用這些條件。但是因爲我正在處理深層次的關係,所以我想保持條件集中。

現在發生的問題是:如果Page模型與例如該Paragraph模型,並從BookController的我想:

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

... CakePHP會告訴我,Paragraph是不相關的Page模型。

如果我可以通過定義一個模型屬性的所有關係順利:

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

這是爲什麼?我需要手動建立這些關係嗎?我的時間(__construct())是否有誤?是否應該在其他地方完成?

親切的問候,巴特

回答

0

是的,你的時間是不正確。您應該之前應用這些配置選項調用父類的構造:

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

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

或使用Model::bindModel()代替,這將創造必要的環節:

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

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