2011-11-14 89 views
0

我正在學習CakePHP,因此我正在製作一個簡單的博客,以便學習基本功能,此博客將擁有包含帖子,用戶,用戶激活碼和分類的表格以及帖子和標籤之間的分類關係。CakePHP模型關係,如何避免不必要的數據?

好吧,那東西現在,我已經成功地正確設置好一切我每次取一個帖子的時候,它會返回大量的數據:

Array 
(
    [Post] => Array 
    (
     [post_id] => 1 
     [post_title] => Test 1 
     [post_nice_name] => test-1 
     [post_author] => 1 
     [post_content] => I'm testing this piece of crap. 
     [post_creation_time] => 2011-11-13 22:50:05 
     [post_last_modification] => 2011-11-13 22:50:05 
     [post_allow_comments] => 1 
     [post_allow_trackback] => 1 
     [post_display] => 1 
    ) 

    [User] => Array 
    (
     [user_id] => 1 
     [user_email] => [email protected] 
     [user_password] => XXXXXXXXXXXXXXXXXX 
     [user_creation_time] => 2011-11-13 10:48:10 
     [user_last_login] => 2011-11-13 22:49:21 
     [user_birthday] => 1993-08-24 03:00:00 
    ) 

    [TaxonomyTags] => Array 
    (
     [0] => Array 
     (
      [tag_id] => 1 
      [tag_name] => test1 
      [tag_description] => This tag is a test 
      [PostsTaxonomyTag] => Array 
      (
       [relation_id] => 1 
       [post_id] => 1 
       [taxonomy_tag_id] => 1 
      )  
     ) 
     [1] => Array 
     (
      [tag_id] => 2 
      [tag_name] => test2 
      [tag_description] => This tag is just another test. 
      [PostsTaxonomyTag] => Array 
      (
       [relation_id] => 2 
       [post_id] => 1 
       [taxonomy_tag_id] => 2 
      )  
     ) 
    ) 
) 

這多少數據實際上是不必要的:我不需要爲每個標籤使用PostsTaxonomyTag數組,我也不需要那麼多的用戶信息,我甚至不需要一些帖子的信息!所以我想知道在傳遞給視圖之前是否有任何方法來過濾這些信息。

回答

3

您可以取消綁定模型befor查找功能,以防止不必要的數據

$this->Model->unbind(array('hasMany' => array('assocModel'))); 

我更喜歡使用的大多數車型中可容納的行爲,迫使你說明你需要找到雖然關係。仔細檢查有關該行爲的文檔。

$this->Model->find(
    'all', 
    array(
     'conditions' => array(
      //set conditions 
     ), 
     'contain' => array(
      'Model2', 
      'model3' 
     ) 
    ) 
); 

您可以在可容納集中設置條件,順序等,使其能夠準確獲取所需的數據。

+0

對可收回行爲的另一投票,非常靈活和強大。 – brism

1

...或者你可以簡單地使用'recursive' => -1在查找選項。

+0

但是,只返回第一個模型...你沒有得到任何東西...所以如果你需要父模型和1關係,那麼設置遞歸不是一個選項。 –

+0

同意,那麼你的答案是最好的選擇:) – 2011-11-14 03:29:37