2011-10-10 17 views
0

以下是一個示例,並未在我的應用程序中使用,但我希望獲得理論並在獲得回答者後將其應用於我自己的應用程序。CakePHP從遙遠的關係獲取數據

因此,需要一個簡單的應用程序有3個表:用戶,位置,以及帖子

和關係是一個帖子有一個用戶和用戶有一個位置,但一個位置不一定有一個用戶。

如果我拉出一個帖子列表,然後顯示該帖子的用戶,這很好。但是,如果我想拉用戶的位置?因爲他們與郵政沒有關係,但是他們是用戶與郵政之間的關係。我會怎麼做?循環

例子:

<?php foreach($posts as $post): ?> 

<?php echo $this->Html->link($post['User']['firstname'], array('controller'=>'users','action'=>'view','userName'=>$post['User']['username'])); ?> in <?php echo $this->Html->link($post['Place']['name'], array('controller'=>'places','action'=>'view',$post['Place']['id'])); ?> 

,這是控制器:

function index() 
    { 
     $posts = $this->paginate(); 

     if (isset($this->params['requested'])) 
     { 
      return $posts; 
     } 
     else 
     { 
      $this->set('posts', $posts); 
     } 
    } 

現在,這是行不通的地點是不確定的!我該怎麼做?

我聽說Containable提到,但一些例子會很棒!

+0

我強烈建議自動加載遠距離關係,因爲這會自動加載一些你並不真正想要的東西。 – NullUserException

回答

0

看看可控制的行爲。它不僅可以讓你解決這個問題,還可以確保只檢索,解析和返回所需的數據,從而幫助你提高應用程序的性能。

例如

function index() 
    { 
     $this->paginate = array(
      'contain' => array('User' => array('Location')), 
     ); 
     $posts = $this->paginate(); 

     if (isset($this->params['requested'])) 
     { 
      return $posts; 
     } 
     else 
     { 
      $this->set('posts', $posts); 
     } 
    }