2014-06-16 2 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의는 ParagraphPage 모델에 관련이없는 나에게 말할 것이다.

내가 모델은 모든 속성 정의하여 관계를 만들 경우 잘 어울린다 :

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

참조