2013-01-04 109 views
3

我想達到的結構,例如,一個組織有很多部門,部門有很多人員。多層次的「有很多」關係

我建立了我的模型結構是這樣的:

組織

<?php 

class Organisation extends AppModel { 

    public $hasMany = array(
      'Department' => array(
       'className' => 'Department', 
       'foreignKey' => 'organisations_id' 
      ) 
     ); 
} 

部門

<?php 

class Department extends AppModel { 

    public $hasMany = array(
      'Person' => array(
       'className' => 'Person', 
       'foreignKey' => 'departments_id' 
      ) 
     ); 
} 

<?php 

class Person extends AppModel { 

} 

然後,我有一個這樣的控制器:

<?php 

class OrganisationsController extends AppController { 

    public $helpers = array('Html', 'Form', 'Session'); 
    public $components = array('Session'); 


    public function index() { 
     $this->set('organisations', $this->Organisation->find('all')); 
    } 

} 

當我打印出$組織,我得到一個數組是這樣的:

Array 
(
    [0] => Array 
     (
      [Organisation] => Array 
       (
        [id] => 1 
        [created] => 2013-01-03 16:02:47 
       ) 

      [Department] => Array 
       (
        [0] => Array 
         (
          [id] => 1 
          [created] => 2013-01-03 16:02:47 
          [organisations_id] => 1 
         ) 

       ) 

     ) 

) 

我新的PHP和CakePHP的,但是你不希望Person數組包含在Organization數組中嗎?如果沒有,是否有另一種方法來實現上述結構(組織結構 - >部門 - >人員)?

有關如何去解決這個問題的任何提示都非常感謝! :)

回答

3

您可能正在尋找recursive

或者你可以利用的containable behaviour

但請看看結果。當使用遞歸時,你可以得到很多你不想要的數據!所以請小心並選擇您實際需要的字段!

遞歸

你會得到這樣的:

<?php 

class OrganisationsController extends AppController { 

    public $helpers = array('Html', 'Form', 'Session'); 
    public $components = array('Session'); 


    public function index() { 
     $this->Organisation->recursive = 2; # or -1, 0, 1, 2, 3 
     $this->set('organisations', $this->Organisation->find('all')); 
    } 
} 

你也可以在宣佈這個發現本身就像這樣:

$this->set('organisations', $this->Organisation->find('all' array(
     'recursive' => 2 # or -1, 0, 1, 2, 3 
    ) 
)); 

中可容納

現在

在你的控制器,你可以這樣做:

$this->set('organisations', $this->Organisation->find('all', array(
     'contain' => array('User') 
    ) 
)); 

但一如既往,條條大道通羅馬。所以請仔細閱讀這些書!

+0

這樣做,雖然我不得不看看我如何過濾結果。謝謝你的協助! – timkl

+1

@timkl過濾結果可以很容易地通過指定您需要的字段來完成。像這樣在你的發現:''包含'=>數組('用戶'=>數組('字段'=>數組('','領域','你','需要')))'。通過簡單地將查找結果記錄在調試日誌中,並簡單地處理查詢,我瞭解了這一點。過一會兒你會得到它的竅門。但我必須提及。有時候我仍然在搞亂包含。他們可以相當混亂,當與所有這些方法混合起來:) – Jelmer

+0

@傑梅爾輝煌地解釋:) – Rikesh

1

Recursive功能將爲你做。

只需在OrganisationsController索引函數中,嘗試像下面那樣做。

$this->Organisation->recursive = 2; 
    $this->set('organisations', $this->Organisation->find('all')); 

注:遞歸可能會影響你的表現,你可以使用unbind方法,通過緊接在讀取所需的數據,以擺脫它。

+1

沒有看到你的答案。也爲你的榮譽:) – Jelmer